The Dutch national flag (DNF) problem is one of the most popular programming problems proposed by Edsger Dijkstra. The flag of the Netherlands consists of three colors: white, red, and blue. The task is to randomly arrange balls of white, red, and blue such that balls of the same color are placed together.
Consider this problem on an array; the task is to sort arrays of 0, 1, and 2 in linear time without any extra space. Since the array is only traversed once, the time complexity of the algorithm given below is O(n).
Note: this algorithm can be implemented on an array that has three unique elements.
The following illustration shows the algorithm in action:
In the code below, three indexes are used (i.e., low
, high
, mid
) to sort the input array – swapping is done according to the above illustration.