Given an array containing only 0’s, 1’s, and 2’s, sort it in linear time and using constant space.

For example,

Input:  { 0, 1, 2, 2, 1, 0, 0, 2, 0, 1, 1, 0 }
 
Output: { 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2 }

Practice this problem

A simple solution would be to perform a counting sort. We count the total number of 0’s, 1’s, and 2’s and then put them in the array in their correct order. The time complexity of this solution is O(n), where n is the size of the input. However, this requires two traversals of the array.

 
We can rearrange the array in a single traversal using an alternative linear-time partition routine that separates the values into three groups:

  • The values less than the pivot,
  • The values equal to the pivot, and
  • The values greater than the pivot.

To solve this particular problem, consider 1 as a pivot. The following linear-time partition routine in C++, Java, and Python is similar to 3–way partitioning for the Dutch national flag problem.

C++


Download  Run Code

Output:

0 0 0 0 0 1 1 1 1 2 2 2

Java


Download  Run Code

Output:

[0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2]

Python


Download  Run Code

Output:

[0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2]

The time complexity of the above solution is O(n) and doesn’t require any extra space, where n is the size of the input.

 
Suggested Read:

Quicksort using Dutch National Flag Algorithm

 
Exercise: Modify the program to rearrange the elements in opposite order (in descending order).