dutch national flag problem code example

Example 1: dutch national flag problem

Initially all array values are treated as unpartitioned:
[unpartitioned values]
Array split into four parts as the iteration proceeds:
[ values < mid | values = mid | unpartitioned values | values > mid ]

procedure three-way-partition(A : array of values, mid : value):
    i ← 0
    j ← 0
    k ← size of A - 1

    while j <= k:
        if A[j] < mid:
            swap A[i] and A[j]
            i ← i + 1
            j ← j + 1
        else if A[j] > mid:
            swap A[j] and A[k]
            k ← k - 1
        else:          
            j ← j + 1

Example 2: sort an array of 0s 1s and 2s

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.
Algorithm:
1)Keep three counter c0 to count 0s, c1 to count 1s and c2 to count 2s
2)Traverse through the array and increase the count of c0 is the 
  element is 0,increase the count of c1 if the element is 1 and 
  increase the count of c2 if the element is 2
3)Now again traverse the array and replace first c0 elements with 0, 
  next c1 elements with 1 and next c2 elements with 2.

//GfG PseudoCode

Tags:

Misc Example