Dutch national flag problem


The Dutch national flag problem is a computer science programming problem proposed by Edsger Dijkstra. The flag of the Netherlands consists of three colors: red, white and blue. Given balls of these three colors arranged randomly in a line, the task is to arrange them such that all balls of the same color are together and their collective color groups are in the correct order.
The solution to this problem is of interest for designing sorting algorithms; in particular, variants of the quicksort algorithm that must be robust to repeated elements may use a three-way partitioning function that groups items less than a given key, equal to the key and greater than the key. Several solutions exist that have varying performance characteristics, tailored to sorting arrays with either small or large numbers of repeated elements.

The array case

This problem can also be viewed in terms of rearranging elements of an array.
Suppose each of the possible elements could be classified into exactly one of three categories.
For example, if all the elements are in 0... 1, the bottom could be defined as elements in 0... 0.1, the middle as 0.1... 0.3
and the top as 0.3 and greater. . The problem is then to produce an array such that all "bottom" elements come before all "middle" elements, which come before all "top" elements.
One algorithm is to have the top group grow down from the top of the array, the bottom group grow up from the bottom, and keep the middle group just above the bottom. The algorithm indexes three locations, the bottom of the top group, the top of the bottom group, and the top of the middle group. Elements that are yet to be sorted fall between the middle and the top group. At each step, examine the element just above the middle. If it belongs to the top group, swap it with the element just below the top. If it belongs in the bottom, swap it with the element just above the bottom. If it is in the middle, leave it. Update the appropriate index. Complexity is Θ moves and examinations.

Pseudocode

The following pseudocode for three-way partitioning which assumes zero-based array indexing was proposed by Dijkstra himself. It uses three indices, and, maintaining the invariant that.
procedure three-way-partition:
i ← 0
j ← 0
k ← size of A
while j < k:
if A < mid:
swap A and A
i ← i + 1
j ← j + 1
else if A > mid:
k ← k - 1
swap A and A

else:
j ← j + 1