Problem Solving: Array Segregation
Learn to solve different array segregation problems.
In this lesson, we’ll practice problems that involve segregating (separating or dividing) the array based on different conditions.
Segregation using extra memory
For instance, given an array, D, we want to segregate the array based on the even and odd values of the array.
Segregating evens and odds
For this, we might want to find the even values from D and store these even values in a separate array, (Es). We can do the same for the odd values and store the odd values in a separate array, (Os). We can make a function that separates the values into even and odd values, (segregateEvensOdds()).
After we’ve separated both the even and odd values, we can replace the values of D with the even and odd values. We can make a separate function to replace the values of the array (replaceEsFollowedByOs()).
Look at the animation below to understand what is happening inside the segregateEvensOdds() function.
Look at the implementation of the segregateEvensOdds() function in the widget below:
We can make a function to display the array’s values (specialDisplay()).
Lastly, we add our function to replace the values:
Look at the animation below to understand what is happening inside the replaceEsFollowedByOs() function.
The complete program is given below:
8 1 589 512 -4 -6 1 4 56
Let’s practice a few of the interesting array segregating problems. If you need debugging at any instant, use the above playground for that.
Practice exercises
Exercise 1: Segregating 0’s and 1’s
Given an array of 0s and 1s, move all the 0s to the left and the 1s to the right.
Sample input:
1 0 0 1 0 1 0 0 0
Sample output:
Segregated 0s Array: 0 0 0 0 0 0
Segregated 1s Array: 1 1 1
Segregated Array: 0 0 0 0 0 0 1 1 1
Write your solution here:
Exercise 2: segregating composites and primes
Given an array of prime and composite numbers, move all primes to the left and the non-primes to the right.
Sample input:
10 5 7 9 6 8
Sample output:
Prime Array: 5 7
Composite Array: 10 9 6 8
Segregated Array: 5 7 10 9 6 8
Write your code here:
Exercise 3: Segregating fruits (mangoes, bananas, and apples)
We have to read and segregate the three different letters representing three fruits. We have b for a banana, m for a mango, and a for an apple. Segregate the values in such a way that all values of b come in the beginning and are followed by the m values and then the a values.
Sample input:
b m m m a a b a m a m b b b a
Sample output:
Segregated Fruits:
Bananas: b b b b b
Mangoes: m m m m m
Apples: a a a a a
Segregated Array: b b b b b m m m m m a a a a a
The code would be the same as the one given above, but you’ll add Bs (bananas), Ms (Mangoes), and As (Apples) array. In the segregateBsMsAs() function, check for the bananas, mangoes, and apples, and save in these arrays.
Here, we need to work with the code as we did before but with three arrays and their counts…
Write your solution here: