![]() |
VOOZH | about |
Given an array A[] consisting 0s, 1s and 2s. The task is to write a function that sorts the given array. 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}
A simple solution is discussed in this(Sort an array of 0s, 1s and 2s (Simple Counting)) post.
Approach:The problem is similar to our old post Segregate 0s and 1s in an array, and both of these problems are variation of famous Dutch national flag problem.
The problem was posed with three colours, here `0', `1' and `2'. The array is divided into four sections:
Part way through the process, some red, white and blue elements are known and are in the "right" place. The section of unknown elements, a[Mid..Hi], is shrunk by examining a[Mid]:
👁 DNF1Examine a[Mid]. There are three possibilities:
👁 DNF2
a[Mid] is (0) red, (1) white or (2) blue.
Case (0) a[Mid] is red, swap a[Lo] and a[Mid]; Lo++; Mid++Case (1) a[Mid] is white, Mid++
👁 DNF3Case (2) a[Mid] is blue, swap a[Mid] and a[Hi]; Hi--
👁 DNF4Continue until Mid>Hi.
Implementation:
Array after seggregation 0 0 0 0 0 1 1 1 1 1 2 2
Approach: Count the number of 0s, 1s and 2s in the given array. Then store all the 0s in the beginning followed by all the 1s then all the 2s.
Implementation:
0 0 0 0 0 1 1 1 1 1 2 2
Please refer complete article on Sort an array of 0s, 1s and 2s for more details!