
The Dutch national flag is composed of three coloured bands in the order:

   red     (top)
   then white,   and
   lastly blue   (at the bottom). 


The problem posed by Edsger Dijkstra is:

Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national flag.
When the problem was first posed, Dijkstra then went on to successively refine a solution, minimising the number of swaps and the number of times the colour of a ball needed to determined and restricting the balls to end in an array, ...



Task
 Generate a randomized order of balls ensuring that they are not in the order of the Dutch national flag.
 Sort the balls in a way idiomatic to your language.
 Check the sorted balls are in the order of the Dutch national flag.


C.f.

 Dutch national flag problem
 Probabilistic analysis of algorithms for the Dutch national flag problem by Wei-Mei Chen. (pdf)


-- Create and populate tables
CREATE TABLE colours (id INTEGER PRIMARY KEY, name VARCHAR(5));
INSERT INTO colours (id, name) VALUES ( 1, 'red'  );
INSERT INTO colours (id, name) VALUES ( 2, 'white');
INSERT INTO colours (id, name) VALUES ( 3, 'blue' );
 
CREATE TABLE balls ( colour INTEGER REFERENCES colours );
INSERT INTO balls ( colour ) VALUES ( 2 );
INSERT INTO balls ( colour ) VALUES ( 2 );
INSERT INTO balls ( colour ) VALUES ( 3 );
INSERT INTO balls ( colour ) VALUES ( 2 );
INSERT INTO balls ( colour ) VALUES ( 1 );
INSERT INTO balls ( colour ) VALUES ( 3 );
INSERT INTO balls ( colour ) VALUES ( 3 );
INSERT INTO balls ( colour ) VALUES ( 2 );
 
-- Show the balls are unsorted
SELECT
	colours.name
FROM
	balls
	JOIN colours ON balls.colour = colours.id;
 
-- Show the balls in dutch flag order
SELECT
	colours.name
FROM
	balls
	JOIN colours ON balls.colour = colours.id
ORDER BY
	colours.id;
 
-- Tidy up
DROP TABLE balls;
DROP TABLE colours;