Question

1. Each baby has brown hair or purple hair. Design a one-pass and in- place and linear time algorithm to sort the babies acco

0 0
Add a comment Improve this question Transcribed image text
Answer #1

As it is given in the problem that the color of the babies' hair is either brown or purple, so let's use 0 for denoting brown-haired babies and 1 for violet-haired babies. So our array which we are supposed to sort now contains only 0 and 1.

Lets first see what the three constraints actually mean..

1. One-pass: It means that we should process(do manipulation or visit) each element a single time only. What this essentially means is that we should come up with an algorithm which will go through all the elements at most 1 time. Once it has visited an element it shouldn't visit the same element again.

2. In-place: It means that all the operations or manipulations that we are doing upon the elements should be done in the given array itself. No extra or temporary space should be used for processing any element. (Exception: Sometimes when we're dealing with huge amounts of data, in-place means that we're not taking too much extra space, some small constant like 2 or 5 extra variables (temporary) can be used. This comes under the space complexity of programs and I think this is a bit above the current required level of the answer, I can expand on this if you want).

3. Linear-time: Linear time means that the time complexity of the algorithm should be linear, which essentially means that for an input of 'n' elements it should take O(n) time. O(n) is called as the Big-O asymptotic notation, which tells that in the worst case possible our algorithm will take order of 'n' time(which can be like 1.5n or 2n or 3n, as long as the constant is not comparable to n).

NOTE: Linear-time and one-pass initially look similar but one-pass allows only one-time processing of data while linear-time can allow any constant amount of time(with that constant being relatively very small as compared to n)

First I would consider linear-time then one-pass because the earlier is easier to get than the latter, and at last we can think about in-place, this should also be the general way in one should think while tackling such questions.

As mentioned, we have to use only two pointers so will take two pointers, lets call them left and right.

We will initialise left with 0(starting index of the array, index of the first element) and right with the last index or the index of the last element which would be n - 1, considering n babies or A.size() - 1(size of array - 1 which is the last index).

Now we will compare the elements at these two positions, i.e. on left and right. Now two cases can arise:

1. The element at A[left] is 1, so we need to put it after all the 0s, so we will simply swap the values of elements present at left and right. Now we can be sure that the element at right is a 1 so we will decrease the value of right pointer by 1, since the element at right is already in its sorted position which is at last. We are still not sure if the element at left is a 0 or a 1, so we won't change the value of A[left].

2. The element at A[left] is 0, here we can simply see that this is sorted, as all 0s should be followed by all 1s and we are getting a 0 at the left-most unprocessed element. Here we increase the value of left by 1.

NOTE: Here we are trying to process the array in such a manner that the elements before the left pointer are all 0s and after the right pointer are all 1s.

We keep doing this until our left pointers become bigger than our right pointer. If this happens then we will break out of the while loop and we can safely say that all the elements in the array have been sorted accordingly.

At maximum either one pointer can go all the from 0 to n-1(in case of left pointer) or from n-1 to 0(in case of right pointer) or they meet somewhere in the middle. Either way, we can say that at each step one element is getting processed(since either left or right pointer values are changed), so it is a linear-time & one-pass algorithm. Also, we are not using any other variable except the left and right pointer so it's in-place too.

WORKING CODE:

void sortArrayByParity(int A[], int n) //Function to sort our array.
{
int left = 0, right = n - 1;
while (left < right) //This loops runs n times
{
if (A[left] == 1)
{   
swap (A[l], A[r]);
--right;
}
else
{
++left;
}
}
for (int i = 0; i < n; ++i) //For printing the sorted array.
cout << A[i] << " ";
}

Add a comment
Know the answer?
Add Answer to:
1. Each baby has brown hair or purple hair. Design a one-pass and in- place and...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • 1. A room contains one-hundred people. Each person has hair that is either black, blonde, brown...

    1. A room contains one-hundred people. Each person has hair that is either black, blonde, brown or red in colour. There are as many people with black hair as there are people with blonde, brown or red hair. Write down a linear system of two equations in four unknowns that encodes this information, and also write down the corresponding augmented matrix. So, the equations I got were: 25b+25l+25r+25d=100 b+l+r+d=100 is that correct? I am not sure.

  • Prepare a design for the Baby Block Robot. The design should be in flow diagram form....

    Prepare a design for the Baby Block Robot. The design should be in flow diagram form. This diagram should help you identify the sequence of steps needed to solve specific situations that the robot will encounter. Be specific. Break down the actions into small steps. Test you design by using example block sequences. Think it through. I would expect the diagram to require multiple pages. If you have a program that supports flow diagrams, like PowerPoint, then use that. Hand...

  • Mechanical Design 1, please answer ASAP and clear. Thank You 3) A producer of helical gears...

    Mechanical Design 1, please answer ASAP and clear. Thank You 3) A producer of helical gears manufactures two different quality rated versions of the same product. Both the gears require three machines designated 1, 2, 3 for their fabrication. Gear A uses three hours, one hour and one hour respectively of machining time. Gear A yields a profit of $50 per unit. Gear B uses one hour, one hour and two hours respectively of machining time. Gear B yields a...

  • (Requirements) Design, Code, Test a C program which will loop forever calculating the resultant saturated pressure...

    (Requirements) Design, Code, Test a C program which will loop forever calculating the resultant saturated pressure of our mythical vessel of special fluid and air to a global variable; vesselPressPsi, from a temperature (degrees Fahrenheit, global variable vesselTempFahr). Temperature will be provided by using a random number generator. Use the modulus operator to place your random number closer to the range vesselTempFahr (45-1800F). [MDV1] This temperature represents an electrical sensor input that was converted to engineering units. The linear interpolation...

  • Name: (4) (10 pts) Design a Moore FSM that has one input A and one output Y, and the output Y should be 1 if A has...

    Name: (4) (10 pts) Design a Moore FSM that has one input A and one output Y, and the output Y should be 1 if A has been 101 during the most recent three consecutive clock cycles or A has been 1 during the two most recent consecutive clock cycles. You only need to write down your state transition diagram. (5) (6 pts) Consider the following sequential circuit. Each two-input OR gate has a propagation delay of 130ps and a...

  • ISOM319 Operations Management Instructions:  For each topic (with bullet point) please use one or two sentences to...

    ISOM319 Operations Management Instructions:  For each topic (with bullet point) please use one or two sentences to describe or define the topic , can be as simple as a definition. You may use the book to help you with concepts you may not remember.    Process Analysis ·       Process Flow Diagram ·       Little’s Law: Flow Unit, Flow Rate, Flow Time ·       Inventory Turns, Direct Labor Cost, Productivity, Yield Capacity Management and Analysis ·       Capacity Management ·       Capacity Analysis: Theoretical vs Actual Capacities, Utilization, Process Capacity, Process Flow...

  • QUESTION 1 Customers arrive at a hair salon according to a Poisson process with an average of 1...

    QUESTION 1 Customers arrive at a hair salon according to a Poisson process with an average of 16 customers per hour. Which of the following is most likely true, based on this information: a. The hair salon serves customers on a walk-in basis (rather than by appointment times) b. If 10 customers arrive in the first hour, it is likely that 22 customers will arrive in the next hour. c. If the salon can serve an average of 20 customers...

  • Part 1: Goal Seek Pampa Parts produces a single product, the NF-9. The product has a...

    Part 1: Goal Seek Pampa Parts produces a single product, the NF-9. The product has a unit variable cost of $70 and annual fixed costs of $343,200. Pampa is subject to a 20 percent tax rate. Suppose the NF-0 sells for $110 per unit. Using the Goal Seek function in Microsoft Excel, how many units of NF-9 must Pampa sell to earn an annual operating profit after taxes of $38,400? Now, suppose Pampa expects to sell 8,150 units of NF-9...

  • Question2 uses structured design implemented in C. Array of records (structs) with file I/O is needed....

    Question2 uses structured design implemented in C. Array of records (structs) with file I/O is needed. The program takes two inputs at a time. The name of a person, and, the coin value as an integer in the range 5 to 95. Input coin values should always be divisible by 5 (integer division). Names are one word strings. An example input is: Jane 30 This input line indicates that 30 cents change is to be given to Jane. Output change...

  • Please Brief: "Brown vs. Board of Education ". located on Page 5 of your book. 1....

    Please Brief: "Brown vs. Board of Education ". located on Page 5 of your book. 1. Make sure to click on the link below to assist in understanding how to properly "brief" as case. 2. Then read the case on Page 5, and brief the case using the "IRAC" format. When you are finished briefing the case, click on the title above and uploaded it into the *** Make sure to begin your brief with a brief facts section telling...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT