VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sort-array-0s-1s-2s-simple-counting/

⇱ Sort an array of 0s, 1s and 2s (Simple Counting) - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sort an array of 0s, 1s and 2s (Simple Counting)

Last Updated : 17 Jan, 2024

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.


Output
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.:

  1. It requires two traversals of array.
  2. This solution may not work if values are a part of the structure. For example, consider a situation where 0 represents Computer Science Stream, 1 represents Electronics and 2 represents Mechanical. We have a list of student objects (or structures) and we want to sort them. We cannot use the above sort as we simply put 0s, 1s, and 2s one by one.

Another Approach:


Output
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)

Comment