![]() |
VOOZH | about |
Given an array A[] consisting of 0s, 1s, and 2s, write a function that sorts A[]. The functions should put all 0s first, then all 1s, and all 2s in last.
Examples:
Input: {0, 1, 2, 0, 1, 2}
Output: {0, 0, 1, 1, 2, 2}Input: {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}
Output: {0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2}
Count the number of 0's, 1's, and 2's. After Counting, put all 0's first, then 1's and lastly 2's in the array. We traverse the array two times.
0 0 0 0 0 1 1 1 1 1 2 2
Time Complexity: O(n)
Auxiliary Space: O(1)
Problems with the above solution.:
Another Approach:
0 0 0 0 0 1 1 1 1 1 2 2
Time Complexity: O(n)
Auxiliary Space: O(n)
Optimal Solution that handles above issues : Sort an array of 0s, 1s and 2s (Dutch National Flag Algorithm)