Dutch National Flag
March 5, 2013
A famous problem given by Edsgar Dijkstra is to sort an array of red, white and blue symbols so that all reds come together, followed by all whites, followed finally by all blues; it’s called the Dutch National Flag problem because the Dutch flag consists of three stripes with red at the top, blue at the bottom, and white in the middle. You are allowed to scan through the array only once, and the only operations permitted are to examine the color of the symbol at a given array location and to swap the symbols at two locations.
Your task is to write a program to perform the sort given above. When you are finished, you are welcome to read or run a suggested solution, or to post your solution or discuss the exercise in the comments below.
[…] today’s Programming Praxis exercise, our goal is to implement a sorting algorithm for lists with three […]
My Haskell solution (see http://bonsaicode.wordpress.com/2013/03/05/dutch-national-flag/ for a version with comments):
[…] Question is from here: […]
My java solution here.
My python solution here( https://github.com/seckcoder/geass/blob/master/dnf4.py ). Actually I implemented the Dutch National Flag Algorithm for 4 colors.
[…] Pages: 1 2 […]
Here’s mine: Partitioning the Dutch national flag
This time, I have both a Racket version and a JavaScript version. The JavaScript has an HTML5 canvas visualizer which was pretty neat to write. It will show the blocks as it sorts, along with the three labels. Let me know if you have any problems running it, I haven’t tested it on anything but Win7/Chrome.
A Common Lisp implementation:
Dijkstra had really nothing better to do (not like me :-p).
Clojure/Script (try online at http://clojurescript.net/).
Tests:
=> (sort-flag [:blue :red :white])
[:red :white :blue]
=> (sort-flag [:blue :red :white :red :blue :white :blue :red])
[:red :red :red :white :white :blue :blue :blue]
=> (sort-flag [:white :blue :red :white :red :blue :white :blue :red])
[:red :red :red :white :white :white :blue :blue :blue]
=> (sort-flag [:white :blue :red :white :red :blue :white :blue :red :white])
[:red :red :red :white :white :white :white :blue :blue :blue]