Dutch national flag problem: Difference between revisions

m
m (added whitespace to the task's preamble, added wording in case the image isn't viewable.)
 
(46 intermediate revisions by 27 users not shown)
Line 23:
* [https://www.google.co.uk/search?rlz=1C1DSGK_enGB472GB472&sugexp=chrome,mod=8&sourceid=chrome&ie=UTF-8&q=Dutch+national+flag+problem#hl=en&rlz=1C1DSGK_enGB472GB472&sclient=psy-ab&q=Probabilistic+analysis+of+algorithms+for+the+Dutch+national+flag+problem&oq=Probabilistic+analysis+of+algorithms+for+the+Dutch+national+flag+problem&gs_l=serp.3...60754.61818.1.62736.1.1.0.0.0.0.72.72.1.1.0...0.0.Pw3RGungndU&psj=1&bav=on.2,or.r_gc.r_pw.r_cp.r_qf.,cf.osb&fp=c33d18147f5082cc&biw=1395&bih=951 Probabilistic analysis of algorithms for the Dutch national flag problem] by Wei-Mei Chen. (pdf)
<br><br>
 
=={{header|11l}}==
{{trans|Python: Construct from ball counts}}
 
<syntaxhighlight lang="11l">V colours_in_order = ‘Red White Blue’.split(‘ ’)
 
F dutch_flag_sort3(items)
[String] r
L(colour) :colours_in_order
r.extend([colour] * items.count(colour))
R r
 
V balls = [‘Red’, ‘Red’, ‘Blue’, ‘Blue’, ‘Blue’, ‘Red’, ‘Red’, ‘Red’, ‘White’, ‘Blue’]
print(‘Original Ball order: ’balls)
V sorted_balls = dutch_flag_sort3(balls)
print(‘Sorted Ball Order: ’sorted_balls)</syntaxhighlight>
 
{{out}}
<pre>
Original Ball order: [Red, Red, Blue, Blue, Blue, Red, Red, Red, White, Blue]
Sorted Ball Order: [Red, Red, Red, Red, Red, White, Blue, Blue, Blue, Blue]
</pre>
 
=={{header|ABAP}}==
This works for ABAP Version 7.40 and above, the color blue is excluded as an option for the last entry to insure an unsorted sequence.
 
<syntaxhighlight lang="abap">
<lang ABAP>
report z_dutch_national_flag_problem.
 
Line 186 ⟶ 208:
 
write:|{ sequence }, is sorted? -> { dutch_national_flag_problem->is_sorted( sequence ) }|, /.
</syntaxhighlight>
</lang>
 
{{output}}
Line 193 ⟶ 215:
 
RRRRRRRRWWWWWWWBBBBB, is sorted? -> X
</pre>
 
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
<syntaxhighlight lang="action!">INCLUDE "D2:SORT.ACT" ;from the Action! Tool Kit
 
PROC PrintArray(BYTE ARRAY a BYTE len)
CHAR ARRAY colors(3)=['R 'W 'B]
BYTE i,index
 
FOR i=0 TO len-1
DO
index=a(i)
Put(colors(index))
OD
RETURN
 
BYTE FUNC IsSorted(BYTE ARRAY a BYTE len)
BYTE i
IF len<=1 THEN
RETURN (1)
FI
FOR i=0 TO len-2
DO
IF a(i)>a(i+1) THEN
RETURN (0)
FI
OD
RETURN (1)
 
PROC Randomize(BYTE ARRAY a BYTE len)
BYTE i
 
FOR i=0 TO len-1
DO
a(i)=Rand(3)
OD
RETURN
 
PROC Main()
DEFINE SIZE="30"
BYTE ARRAY a(SIZE)
 
Put(125) PutE() ;clear the screen
DO
Randomize(a,SIZE)
UNTIL IsSorted(a,SIZE)=0
OD
PrintE("Unsorted:") PrintArray(a,SIZE)
PutE() PutE()
 
SortB(a,SIZE,0)
PrintE("Sorted:") PrintArray(a,SIZE)
PutE() PutE()
 
IF IsSorted(a,SIZE) THEN
PrintE("Sorting is valid")
ELSE
PrintE("Sorting is invalid!")
FI
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Dutch_national_flag_problem.png Screenshot from Atari 8-bit computer]
<pre>
Unsorted:
RBWBWRRRRRWBWRWRRBBWBBBRRWWRRR
 
Sorted:
RRRRRRRRRRRRRRWWWWWWWWBBBBBBBB
 
Sorting is valid
</pre>
 
=={{header|Ada}}==
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO, Ada.Numerics.Discrete_Random, Ada.Command_Line;
 
procedure Dutch_National_Flag is
Line 295 ⟶ 389:
 
Print("After Sorting: ", A);
end Dutch_National_Flag;</langsyntaxhighlight>
 
{{out}}
Line 309 ⟶ 403:
After Sorting: WHITE, WHITE, WHITE, WHITE, BLUE, BLUE, BLUE</pre>
 
=={{header|ALGOL 68}}==
<syntaxhighlight lang="algol68">BEGIN # Dutch national flag problem: sort a set of randomly arranged red, white and blue balls into order #
# ball sets are represented by STRING items, red by "R", white by "W" and blue by "B" #
# returns the balls sorted into red, white and blue order #
PROC sort balls = ( STRING balls )STRING:
BEGIN
[ 1 : ( UPB balls + 1 ) - LWB balls ]CHAR result, white, blue;
INT r pos := 0, w pos := 0, b pos := 0;
# copy the red balls into the result and split the white and blue #
# into separate lists #
FOR pos FROM LWB balls TO UPB balls DO
CHAR b = balls[ pos ];
IF b = "R" THEN
# red ball - add to the result #
result[ r pos +:= 1 ] := b
ELIF b = "W" THEN
# white ball #
white[ w pos +:= 1 ] := b
ELSE
# must be blue #
blue[ b pos +:= 1 ] := b
FI
OD;
# add the white balls to the list #
IF w pos > 0 THEN
# there were some white balls - add them to the result #
result[ r pos + 1 : r pos + w pos ] := white[ 1 : w pos ];
r pos +:= w pos
FI;
# add the blue balls to the list #
IF b pos > 0 THEN
# there were some blue balls - add them to the end of the result #
result[ r pos + 1 : r pos + b pos ] := blue[ 1 : b pos ];
r pos +:= b pos
FI;
result[ 1 : r pos ]
END # sort balls # ;
# returns TRUE if balls is sorted, FALSE otherwise #
PROC sorted balls = ( STRING balls )BOOL:
BEGIN
BOOL result := TRUE;
FOR i FROM LWB balls + 1 TO UPB balls
WHILE result := ( CHAR prev = balls[ i - 1 ];
CHAR curr = balls[ i ];
prev = curr
OR ( prev = "R" AND curr = "W" )
OR ( prev = "R" AND curr = "B" )
OR ( prev = "W" AND curr = "B" )
)
DO SKIP OD;
result
END # sorted balls # ;
# constructs an unsorted random string of n balls #
PROC random balls = ( INT n )STRING:
BEGIN
STRING result := n * "?";
WHILE FOR i TO n DO
result[ i ] := IF INT r = ENTIER( next random * 3 ) + 1;
r = 1
THEN "R"
ELIF r = 2
THEN "W"
ELSE "B"
FI
OD;
sorted balls( result )
DO SKIP OD;
result
END # random balls # ;
# tests #
FOR i FROM 11 BY 3 TO 17 DO
STRING balls;
balls := random balls( i );
print( ( "before: ", balls, IF sorted balls( balls ) THEN " initially sorted??" ELSE "" FI, newline ) );
balls := sort balls( balls );
print( ( "after: ", balls, IF sorted balls( balls ) THEN "" ELSE " NOT" FI, " sorted", newline ) )
OD
END</syntaxhighlight>
{{out}}
<pre>
before: BWWRWRBWBRR
after: RRRRWWWWBBB sorted
before: BBRBWWRWBRRBBW
after: RRRRWWWWBBBBBB sorted
before: WRRWRRRBBWBRRWBWB
after: RRRRRRRWWWWWBBBBB sorted
</pre>
 
=={{header|AppleScript}}==
<syntaxhighlight lang="applescript">use AppleScript version "2.3.1" -- OS X 10.9 (Mavericks) or later.
use sorter : script ¬
"Custom Iterative Ternary Merge Sort" --<www.macscripter.net/t/timsort-and-nigsort/71383/3>
 
on DutchNationalFlagProblem(numberOfBalls)
script o
property colours : {"red", "white", "blue"}
property balls : {}
-- Custom comparison handler for the sort.
on isGreater(a, b)
return ((a ≠ b) and ((a is "blue") or (b is "red")))
end isGreater
end script
repeat numberOfBalls times
set end of o's balls to some item of o's colours
end repeat
tell sorter to sort(o's balls, 1, numberOfBalls, {comparer:o})
return o's balls
end DutchNationalFlagProblem
 
DutchNationalFlagProblem(100)</syntaxhighlight>
 
{{output}}
<pre>Log:
(*blue, blue, blue, white, blue, white, white, white, red, blue, red, red, white, white, blue, white, blue, white, red, blue, white, white, blue, white, red, blue, white, white, white, blue, blue, red, blue, red, red, blue, white, white, red, white, red, red, red, blue, red, blue, red, blue, red, white, blue, white, red, white, red, white, white, blue, red, blue, blue, red, white, blue, red, white, blue, white, red, blue, white, white, white, blue, red, white, white, white, white, blue, red, red, white, red, red, red, white, white, red, blue, white, red, red, red, red, red, white, red, red, white*)
 
Result:
{"red", "red", "red", "red", "red", "red", "red", "red", "red", "red", "red", "red", "red", "red", "red", "red", "red", "red", "red", "red", "red", "red", "red", "red", "red", "red", "red", "red", "red", "red", "red", "red", "red", "red", "red", "white", "white", "white", "white", "white", "white", "white", "white", "white", "white", "white", "white", "white", "white", "white", "white", "white", "white", "white", "white", "white", "white", "white", "white", "white", "white", "white", "white", "white", "white", "white", "white", "white", "white", "white", "white", "white", "white", "blue", "blue", "blue", "blue", "blue", "blue", "blue", "blue", "blue", "blue", "blue", "blue", "blue", "blue", "blue", "blue", "blue", "blue", "blue", "blue", "blue", "blue", "blue", "blue", "blue", "blue", "blue"}</pre>
 
In the unlikely event of this being something you'll want done often at very high speeds, Dijkstra's own algorithm for the task is somewhat faster:
 
<syntaxhighlight lang="applescript">on threeWayPartition(theList, order) -- Dijkstra's algorithm.
script o
property lst : theList
end script
set {v1, v2, v3} to order
set {i, j, k} to {1, 1, (count o's lst)}
repeat until (j > k)
set this to o's lst's item j
if (this = v3) then
set o's lst's item j to o's lst's item k
set o's lst's item k to this
set k to k - 1
else
if (this = v1) then
set o's lst's item j to o's lst's item i
set o's lst's item i to this
set i to i + 1
end if
set j to j + 1
end if
end repeat
return -- Input list sorted in place.
end threeWayPartition
 
on DutchNationalFlagProblem(numberOfBalls)
script o
property balls : {}
end script
set colours to {"red", "white", "blue"}
repeat numberOfBalls times
set end of o's balls to some item of colours
end repeat
threeWayPartition(o's balls, colours)
return o's balls
end DutchNationalFlagProblem
 
DutchNationalFlagProblem(100)</syntaxhighlight>
 
=={{header|Applesoft BASIC}}==
{{trans|ZX_Spectrum_Basic}}
<syntaxhighlight lang="applesoftbasic"> 100 READ C$(0),C$(1),C$(2)
110 DATARED,WHITE,BLUE,0
120 PRINT "RANDOM:
130 FOR N = 0 TO 9
140 LET B%(N) = RND (1) * 3
150 GOSUB 250
160 NEXT N
170 PRINT
180 READ S
190 PRINT "SORTED:
200 FOR I = 0 TO 2
210 FOR N = 0 TO 9
220 ON B%(N) = I GOSUB 250
230 NEXT N,I
240 END
250 PRINT SPC( S)C$(B%(N));
260 LET S = 1
270 RETURN </syntaxhighlight>
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotKeylang="autohotkey">RandGen(MaxBalls){
Random,k,3,MaxBalls
Loop,% k{
Line 323 ⟶ 602:
F:=RTrim(F,",")
Sort,F,N D`,
MsgBox,% F:=RegExReplace(RegExReplace(RegExReplace(F,"(1)","Red"),"(2)","White"),"(3)","Blue")</langsyntaxhighlight>
 
=={{header|AutoIt}}==
Given each color a value in descending order ( Red = 1, White = 2 And Blue = 3)
<syntaxhighlight lang="autoit">
<lang Autoit>
#include <Array.au3>
Dutch_Flag(50)
Line 352 ⟶ 631:
_ArrayDisplay($avArray)
EndFunc ;==>Dutch_Flag
</syntaxhighlight>
</lang>
 
=={{header|AWK}}==
{{works with|gawk}}
<langsyntaxhighlight lang="awk">
BEGIN {
weight[1] = "red"; weight[2] = "white"; weight[3] = "blue";
Line 404 ⟶ 683:
return 1
}
</syntaxhighlight>
</lang>
 
Output:
 
<syntaxhighlight lang="text">
BEFORE: blue red white red white blue red white blue white
 
Line 414 ⟶ 693:
 
Sorting is valid.
</syntaxhighlight>
</lang>
 
=={{header|BaConBASIC}}==
==={{header|BaCon}}===
<lang qbasic>DECLARE color$[] = { "red", "white", "blue" }
<syntaxhighlight lang="qbasic">DECLARE color$[] = { "red", "white", "blue" }
 
DOTIMES 16
Line 425 ⟶ 705:
PRINT "Unsorted: ", ball$
 
PRINT " Sorted: ", REPLACE$(SORT$(REPLACE$(ball$, "blue", "z")), "z", "blue")</langsyntaxhighlight>
{{out}}
<pre>
Line 432 ⟶ 712:
</pre>
 
==={{header|BBC BASICBASIC256}}===
<syntaxhighlight lang="basic256">arraybase 1
dim flag = {"Red","White","Blue"}
dim balls(9)
 
print "Random: |";
for i = 1 to 9
kolor = (rand * 3) + 1
balls[i] = flag[kolor]
print balls[i]; " |";
next i
print
 
print "Sorted: |";
for i = 1 to 3
kolor = flag[i]
for j = 1 to 9
if balls[j] = kolor then print balls[j]; " |";
next j
next i</syntaxhighlight>
 
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> INSTALL @lib$+"SORTLIB"
Sort% = FN_sortinit(0,0)
Line 471 ⟶ 772:
prev% = weight%
NEXT
IF NOT sorted% PRINT "Error: Balls are not in correct order!"</langsyntaxhighlight>
{{out}}
<pre>
Line 479 ⟶ 780:
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h> //printf()
#include <stdlib.h> //srand(), rand(), RAND_MAX, qsort()
#include <stdbool.h> //true, false
Line 532 ⟶ 833:
}
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>Accidentally still sorted:rrrww
Non-sorted: rbwww
Sorted: rwwwb</pre>
 
=={{header|C++}}==
<syntaxhighlight lang="cpp">#include <algorithm>
#include <iostream>
 
// Dutch national flag problem
template <typename BidIt, typename T>
void dnf_partition(BidIt first, BidIt last, const T& low, const T& high)
{
for (BidIt next = first; next != last; ) {
if (*next < low) {
std::iter_swap(first++, next++);
} else if (!(*next < high)) {
std::iter_swap(next, --last);
} else {
++next;
}
}
}
 
enum Colors { RED, WHITE, BLUE };
 
void print(const Colors *balls, size_t size)
{
static const char *label[] = { "red", "white", "blue" };
 
std::cout << "Balls:";
for (size_t i = 0; i < size; ++i) {
std::cout << ' ' << label[balls[i]];
}
std::cout << "\nSorted: " << std::boolalpha << std::is_sorted(balls, balls + size) << '\n';
}
 
int main()
{
Colors balls[] = { RED, WHITE, BLUE, RED, WHITE, BLUE, RED, WHITE, BLUE };
 
std::random_shuffle(balls, balls + 9);
print(balls, 9);
 
dnf_partition(balls, balls + 9, WHITE, BLUE);
print(balls, 9);
}</syntaxhighlight>
{{out}}
<pre>
Balls: blue white red blue red blue white red white
Sorted: false
Balls: red red red white white white blue blue blue
Sorted: true
</pre>
 
=={{header|C_sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 613 ⟶ 965:
}
}
</syntaxhighlight>
</lang>
 
=={{header|C++}}==
<lang cpp>#include <algorithm>
#include <iostream>
 
// Dutch national flag problem
template <typename BidIt, typename T>
void dnf_partition(BidIt first, BidIt last, const T& low, const T& high)
{
for (BidIt next = first; next != last; ) {
if (*next < low) {
std::iter_swap(first++, next++);
} else if (!(*next < high)) {
std::iter_swap(next, --last);
} else {
++next;
}
}
}
 
enum Colors { RED, WHITE, BLUE };
 
void print(const Colors *balls, size_t size)
{
static const char *label[] = { "red", "white", "blue" };
 
std::cout << "Balls:";
for (size_t i = 0; i < size; ++i) {
std::cout << ' ' << label[balls[i]];
}
std::cout << "\nSorted: " << std::boolalpha << std::is_sorted(balls, balls + size) << '\n';
}
 
int main()
{
Colors balls[] = { RED, WHITE, BLUE, RED, WHITE, BLUE, RED, WHITE, BLUE };
 
std::random_shuffle(balls, balls + 9);
print(balls, 9);
 
dnf_partition(balls, balls + 9, WHITE, BLUE);
print(balls, 9);
}</lang>
{{out}}
<pre>
Balls: blue white red blue red blue white red white
Sorted: false
Balls: red red red white white white blue blue blue
Sorted: true
</pre>
 
=={{header|Ceylon}}==
Be sure to add ceylon.random in your module.ceylon file.
<langsyntaxhighlight lang="ceylon">import ceylon.random {
 
DefaultRandom
Line 748 ⟶ 1,050:
print(sortedBalls1);
print(sortedBalls2);
}</langsyntaxhighlight>
 
 
=={{header|Clojure}}==
<syntaxhighlight lang="clojure">(defn dutch-flag-order [color]
(get {:red 1 :white 2 :blue 3} color))
 
(defn sort-in-dutch-flag-order [balls]
(sort-by dutch-flag-order balls))
 
;; Get a collection of 'n' balls of Dutch-flag colors
(defn random-balls [num-balls]
(repeatedly num-balls
#(rand-nth [:red :white :blue])))
 
;; Get random set of balls and insure they're not accidentally sorted
(defn starting-balls [num-balls]
(let [balls (random-balls num-balls)
in-dutch-flag-order? (= balls
(sort-in-dutch-flag-order balls))]
(if in-dutch-flag-order?
(recur num-balls)
balls)))</syntaxhighlight>
 
{{out}}
<pre>
(def balls (starting-balls 20))
balls ; (:blue :red :red :blue :white :blue :white :blue :white :red
; :blue :red :white :white :white :red :blue :white :blue :blue)
 
(sort-in-dutch-flag-order balls) ; (:red :red :red :red :red :white :white :white :white :white
; :white :white :blue :blue :blue :blue :blue :blue :blue :blue)
</pre>
 
=={{header|Common Lisp}}==
{{trans|Clojure}}
<syntaxhighlight lang="lisp">
(defun dutch-flag-order (color)
(case color (:red 1) (:white 2) (:blue 3)))
 
(defun sort-in-dutch-flag-order (balls)
(sort (copy-list balls) #'< :key #'dutch-flag-order))
 
(defun make-random-balls (count)
(loop :repeat count
:collect (nth (random 3) '(:red :white :blue))))
 
(defun make-balls (count)
(loop :for balls = (make-random-balls count)
:while (equal balls (sort-in-dutch-flag-order balls))
:finally (return balls)))
 
;; Alternative version showcasing iterate's finding clause
(defun make-balls2 (count)
(iter (for balls = (make-random-balls count))
(finding balls such-that (not (equal balls (sort-in-dutch-flag-order balls))))))
</syntaxhighlight>
{{out}}
<pre>
CL-USER> (defvar *balls* (make-balls 20))
*BALLS*
CL-USER> *balls*
(:WHITE :WHITE :WHITE :WHITE :RED :BLUE :RED :RED :WHITE :WHITE :RED :BLUE :RED
:RED :BLUE :WHITE :BLUE :BLUE :BLUE :BLUE)
CL-USER> (sort-in-dutch-flag-order *balls*)
(:RED :RED :RED :RED :RED :RED :WHITE :WHITE :WHITE :WHITE :WHITE :WHITE :WHITE
:BLUE :BLUE :BLUE :BLUE :BLUE :BLUE :BLUE)
</pre>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.random, std.algorithm, std.traits, std.array;
 
enum DutchColors { red, white, blue }
Line 781 ⟶ 1,150:
writeln("\nSorted Ball Order:\n", balls);
assert(balls[].isSorted, "Balls not sorted.");
}</langsyntaxhighlight>
{{out}}
<pre>Original Ball order:
Line 790 ⟶ 1,159:
 
===Bidirectional Range Version===
<langsyntaxhighlight lang="d">import std.stdio, std.random, std.algorithm, std.range,
std.array, std.traits;
 
Line 861 ⟶ 1,230:
assert(balls[0 .. n].isSorted());
}
}</langsyntaxhighlight>
The output is the same.
 
Line 867 ⟶ 1,236:
This version uses more contract programming and asserts to verify the code correctness.
With hints from: toccata.lri.fr/gallery/flag.en.html
<langsyntaxhighlight lang="d">import std.stdio, std.random, std.algorithm, std.traits, std.range;
 
enum Color : ubyte { blue, white, red }
Line 959 ⟶ 1,328:
writeln("\nSorted Ball Order:\n", balls);
assert(balls[].isSorted, "Balls not sorted.");
}</langsyntaxhighlight>
The output is the same.
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|Classes,SysUtils,StdCtrls}}
Encodes the colors to strings of "1" "2" and "3" to allow them to be sorted. Then it sses Delphi TStringList to sort the colors.
 
<syntaxhighlight lang="Delphi">
 
const TestOrder: array [0..11] of string =
('Blue','Blue','White','Blue','White','Blue',
'Red','White','White','Blue','White','Red');
 
 
procedure DoDutchFlag(Memo: TMemo; Order: array of string);
{Solve dutch flag color order using TStringList component}
{Encode colors "Red", "White" and "Blue" to "1", "2", and "3" }
{This allows them to be sorted in the TString List}
var I: integer;
var SL: TStringList;
var S2: string;
 
function DecodeList(SL: TStringList): string;
{Convert encoded colors 1, 2 and 3 to Red, White and Blue}
var I: integer;
begin
Result:='';
for I:=0 to SL.Count-1 do
begin
if I>0 then Result:=Result+',';
if SL[I]='1' then Result:=Result+'Red'
else if SL[I]='2' then Result:=Result+'White'
else Result:=Result+'Blue'
end;
end;
 
begin
SL:=TStringList.Create;
try
{Encode colors from array of strings}
for I:=0 to High(TestOrder) do
begin
if Order[I]='Red' then SL.Add('1')
else if Order[I]='White' then SL.Add('2')
else SL.Add('3');
end;
Memo.Lines.Add('Original Order:');
Memo.Lines.Add('['+DecodeList(SL)+']');
SL.Sort;
Memo.Lines.Add('Original Order:');
Memo.Lines.Add('['+DecodeList(SL)+']');
finally SL.Free; end;
end;
 
 
procedure ShowDutchFlag(Memo: TMemo);
begin
DoDutchFlag(Memo,TestOrder);
end;
 
</syntaxhighlight>
{{out}}
<pre>
Original Order:
[Blue,Blue,White,Blue,White,Blue,Red,White,White,Blue,White,Red]
Original Order:
[Red,Red,White,White,White,White,White,Blue,Blue,Blue,Blue,Blue]
</pre>
 
 
=={{header|EasyLang}}==
<syntaxhighlight>
col$[] = [ "red" "white" "blue" ]
for i to 8
b[] &= randint 3
.
for b in b[]
write col$[b] & " "
if b < b0
not_sorted = 1
.
b0 = b
.
print ""
print ""
if not_sorted = 0
print "already sorted"
else
for i = 1 to len b[] - 1
for j = i + 1 to len b[]
if b[j] < b[i]
swap b[j] b[i]
.
.
.
for b in b[]
write col$[b] & " "
.
.
</syntaxhighlight>
 
=={{header|Elixir}}==
{{trans|Erlang}}
<langsyntaxhighlight lang="elixir">defmodule Dutch_national_flag do
defp ball(:red), do: 1
defp ball(:white), do: 2
Line 996 ⟶ 1,464:
end
 
Dutch_national_flag.problem</langsyntaxhighlight>
 
{{out}}
Line 1,007 ⟶ 1,475:
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">-module(dutch).
-export([random_balls/1, is_dutch/1, dutch/1]).
 
Line 1,032 ⟶ 1,500:
dutch(R, W, B, [red | L]) -> dutch([red|R], W, B, L);
dutch(R, W, B, [white | L]) -> dutch(R, [white|W], B, L);
dutch(R, W, B, [blue | L]) -> dutch(R, W, [blue|B], L).</langsyntaxhighlight>
 
Sample usage:
<langsyntaxhighlight lang="erlang">main(_) ->
L = random_balls(10),
case is_dutch(L) of
true -> io:format("The random sequence ~p is already in the order of the Dutch flag!~n", [L]);
false -> io:format("The starting random sequence is ~p;~nThe ordered sequence is ~p.~n", [L, dutch(L)])
end.</langsyntaxhighlight>
 
{{out}}
Line 1,049 ⟶ 1,517:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">(* Since the task description here does not impose Dijsktra's original restrictions
* Changing the order is only allowed by swapping 2 elements
* Every element must only be inspected once
Line 1,082 ⟶ 1,550:
let sorted = rs @ ws @ bs
printfn "The sequence %A is sorted: %b" sorted (isDutch sorted)
0</langsyntaxhighlight>
{{out}}
<pre>Sort the sequence of 10 balls: [Red; White; Red; Blue; White; White; Blue; Blue; White; White]
The sequence [Red; Red; White; White; White; White; White; Blue; Blue; Blue] is sorted: true</pre>
 
=={{header|Factor}}==
{{works with|Factor|0.99 2020-01-23}}
<syntaxhighlight lang="factor">USING: combinators grouping kernel math prettyprint random
sequences ;
 
: sorted? ( seq -- ? ) [ <= ] monotonic? ;
 
: random-non-sorted-integers ( length n -- seq )
2dup random-integers
[ dup sorted? ] [ drop 2dup random-integers ] while 2nip ;
 
: dnf-sort! ( seq -- seq' )
[ 0 0 ] dip [ length 1 - ] [ ] bi
[ 2over <= ] [
pick over nth {
{ 0 [ reach reach pick exchange [ [ 1 + ] bi@ ] 2dip ] }
{ 1 [ [ 1 + ] 2dip ] }
[ drop 3dup exchange [ 1 - ] dip ]
} case
] while 3nip ;
 
10 3 random-non-sorted-integers dup . dnf-sort! .</syntaxhighlight>
{{out}}
<pre>
{ 1 2 2 0 0 0 1 0 0 1 }
{ 0 0 0 0 0 1 1 1 2 2 }
</pre>
 
=={{header|Forth}}==
Line 1,095 ⟶ 1,591:
https://github.com/bfox9900/CAMEL99-V2/blob/master/Video/DIJKSTRAFLAG%20.mp4
 
<syntaxhighlight lang="text">\ Dutch flag DEMO for CAMEL99 Forth
\ *SORTS IN PLACE FROM Video MEMORY*
 
Line 1,243 ⟶ 1,739:
CR ." Completed"
;
</syntaxhighlight>
</lang>
 
=={{header|Fortran}}==
Line 1,249 ⟶ 1,745:
 
Abhor code duplication. I've repeated code anyway to demonstrate FORTRAN pointers, which behave like an alias. A subroutine with traditional arguments including the number of valid elements of the array is appropriate. I'd use one long array instead of 3 arrays and the size intrinsic.
<syntaxhighlight lang="text">
!-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Mon Jun 3 11:18:24
Line 1,355 ⟶ 1,851:
 
end program Netherlands
</syntaxhighlight>
</lang>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">
' El problema planteado por Edsger Dijkstra es:
' "Dado un número de bolas rojas, azules y blancas en orden aleatorio,
Line 1,382 ⟶ 1,878:
Next i
End
</syntaxhighlight>
</lang>
 
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=e57a862aff12647fa80c84a595161cb9 Click this link to run this code]'''
<langsyntaxhighlight lang="gambas">Public Sub Main()
Dim Red As String = "0"
Dim White As String = "1"
Line 1,411 ⟶ 1,907:
Next
 
End</langsyntaxhighlight>
Output:
<pre>
Line 1,419 ⟶ 1,915:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,506 ⟶ 2,002:
f.sort3()
fmt.Println(f)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,523 ⟶ 2,019:
The function "sort" works with anything that belongs to the Eq and Ord classes.
The function "randomRIO" takes a range of two integers to give a random value within the range. We make Color an instance of Enum so that we can give Red, White and Blue as integers to randomRIO and convert the random number back to Red, White or Blue.
<langsyntaxhighlight Haskelllang="haskell">import Data.List (sort)
import System.Random (randomRIO)
import System.IO.Unsafe (unsafePerformIO)
Line 1,548 ⟶ 2,044:
False -> do
putStrLn $ "The starting random sequence is " ++ show a ++ "\n"
putStrLn $ "The ordered sequence is " ++ show (dutch a)</langsyntaxhighlight>
{{out}}
<pre>
Line 1,559 ⟶ 2,055:
 
To understand ''why'' Dijsktra was interested in the problem, here's an example showing difficiency of using generic sort:
<langsyntaxhighlight lang="haskell">inorder n = and $ zipWith (<=) n (tail n) -- or use Data.List.Ordered
 
mk012 :: Int -> Int -> [Int] -- definitely unordered
Line 1,579 ⟶ 2,075:
-- print $ inorder $ dutch1 s -- O(n)
print $ inorder $ dutch2 s -- O(n)
where s = mk012 10000000 42</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
Line 1,591 ⟶ 2,087:
force at least one of each color ball, change "?n-1" to "?n" in the 3rd line.
 
<langsyntaxhighlight lang="unicon">procedure main(a)
n := integer(!a) | 20
every (nr|nw|nb) := ?n-1
Line 1,612 ⟶ 2,108:
every (s := "") ||:= (find(c := !cset(w),w),c)
return s
end</langsyntaxhighlight>
 
A few sample runs:
Line 1,634 ⟶ 2,130:
=={{header|J}}==
We shall define a routine to convert the values 0 1 2 to ball names:
<langsyntaxhighlight Jlang="j">i2b=: {&(;:'red white blue')</langsyntaxhighlight>
and its inverse
<langsyntaxhighlight Jlang="j">b2i=: i2b inv</langsyntaxhighlight>
Next, we need a random assortment of balls:
<langsyntaxhighlight Jlang="j"> BALLS=: i2b ?20#3
BALLS
┌────┬───┬────┬───┬───┬─────┬─────┬─────┬────┬────┬─────┬────┬────┬───┬────┬───┬─────┬───┬────┬───┐
│blue│red│blue│red│red│white│white│white│blue│blue│white│blue│blue│red│blue│red│white│red│blue│red│
└────┴───┴────┴───┴───┴─────┴─────┴─────┴────┴────┴─────┴────┴────┴───┴────┴───┴─────┴───┴────┴───┘</langsyntaxhighlight>
And we want to sort them in their canonical order:
<langsyntaxhighlight Jlang="j"> /:~&.b2i BALLS
┌───┬───┬───┬───┬───┬───┬───┬─────┬─────┬─────┬─────┬─────┬────┬────┬────┬────┬────┬────┬────┬────┐
│red│red│red│red│red│red│red│white│white│white│white│white│blue│blue│blue│blue│blue│blue│blue│blue│
└───┴───┴───┴───┴───┴───┴───┴─────┴─────┴─────┴─────┴─────┴────┴────┴────┴────┴────┴────┴────┴────┘</langsyntaxhighlight>
Note that if we were not using J's built in sort, we would probably want to use [[Counting_sort|bin sort]] here.
 
Anyways, we can test that they are indeed sorted properly:
<langsyntaxhighlight Jlang="j"> assert@(-: /:~)&b2i /:~&.b2i BALLS</langsyntaxhighlight>
 
=={{header|Java}}==
The elements of an <code>enum</code> implement <code>Comparable</code> so the build-in sort works. You can also use this comparability to check the sort has worked.
<langsyntaxhighlight lang="java">import java.util.Arrays;
import java.util.Random;
 
Line 1,684 ⟶ 2,180:
System.out.println("Correctly sorted: " + sorted);
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,693 ⟶ 2,189:
=={{header|Javascript}}==
===ES6===
<langsyntaxhighlight lang="javascript">const dutchNationalFlag = () => {
 
/**
Line 1,774 ⟶ 2,270:
};
dutchNationalFlag();
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,784 ⟶ 2,280:
Is sorted: true
</pre>
=={{header|jq}}==
{{works with|jq}}
'''Also works with gojq, the Go implementation of jq.'''
 
'''Adapted from [[#Wren|Wren]]'''
 
In the following, /dev/random is used as a source of entropy.
In a bash or bash-like environment, a suitable invocation would
be as follows:
<pre>
< /dev/random tr -cd '0-9' | fold -w 1 | jq -Mcnr -f dnf.jq
</pre>
'''dnf.jq'''
<syntaxhighlight lang=jq>
# Output: a PRN in range(0; .)
def prn:
if . == 1 then 0
else . as $n
| (($n-1)|tostring|length) as $w
| [limit($w; inputs)] | join("") | tonumber
| if . < $n then . else ($n | prn) end
end;
 
def colors: ["Red", "White", "Blue"];
 
def colorMap: {"Red": 0, "White": 1, "Blue": 2 };
 
def task($nballs):
def sorted:
. == sort_by(colorMap[.]);
def generate:
[range(0; $nballs) | colors[ 3|prn ] ]
| if sorted then generate else . end;
generate
| "Before sorting : \(.)",
"After sorting : \(sort_by(colorMap[.]))" ;
 
task(9)
</syntaxhighlight>
{{output}}
<pre>
Before sorting : ["Blue","Red","Blue","White","Blue","White","Red","White","Blue"]
After sorting : ["Red","Red","White","White","White","Blue","Blue","Blue","Blue"]
</pre>
 
=={{header|Julia}}==
Line 1,791 ⟶ 2,329:
 
'''Function'''
<syntaxhighlight lang="julia">
<lang Julia>
const COLORS = ["red", "white", "blue"]
 
Line 1,816 ⟶ 2,354:
dutchsort!(copy(a), lo, hi)
end
</syntaxhighlight>
</lang>
 
'''Main'''
<syntaxhighlight lang="julia">
<lang Julia>
function formatdf(a::Array{ASCIIString,1})
i = 0
Line 1,850 ⟶ 2,388:
@time e = sort(d, by=x->findfirst(COLORS, x))
println(formatdf(e))
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,870 ⟶ 2,408:
=={{header|Kotlin}}==
{{trans|D}}
<langsyntaxhighlight lang="scala">// version 1.1.4
 
import java.util.Random
Line 1,922 ⟶ 2,460:
// print the colors of the balls after sorting
println("After sorting : ${balls.contentToString()}")
}</langsyntaxhighlight>
 
Sample output:
Line 1,931 ⟶ 2,469:
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">define orderdutchflag(a) => {
local(r = array, w = array, b = array)
with i in #a do => {
Line 1,946 ⟶ 2,484:
}
 
orderdutchflag(array('Red', 'Red', 'Blue', 'Blue', 'Blue', 'Red', 'Red', 'Red', 'White', 'Blue'))</langsyntaxhighlight>
{{out}}
<pre>array(Red, Red, Red, Red, Red, White, Blue, Blue, Blue, Blue)</pre>
 
=={{header|Logo}}==
<langsyntaxhighlight lang="logo">; We'll just use words for the balls
make "colors {red white blue}
 
Line 2,018 ⟶ 2,556:
setitem :a :array item :b :array
setitem :b :array :temp
end</langsyntaxhighlight>
 
Test code:
<syntaxhighlight lang="text">do.while [
make "list random_balls 10
] [dutch? :list]
Line 2,027 ⟶ 2,565:
print (sentence [Start list:] arraytolist :list)
print (sentence [Sorted:] arraytolist dutch :list)
bye</langsyntaxhighlight>
 
{{out}}
<pre>Start list: white blue red red red white blue red red white
Sorted: red red red red red white white white blue blue</pre>
 
=={{header|Lua}}==
The task seems to allow for some interpretation, so attempting to follow as literally as possible.
<syntaxhighlight lang="lua">-- "1. Generate a randomized order of balls.."
math.randomseed(os.time())
N, balls, colors = 10, {}, { "red", "white", "blue" }
for i = 1, N do balls[i] = colors[math.random(#colors)] end
-- "..ensuring that they are not in the order of the Dutch national flag."
order = { red=1, white=2, blue=3 }
function issorted(t)
for i = 2, #t do
if order[t[i]] < order[t[i-1]] then return false end
end
return true
end
local function shuffle(t)
for i = #t, 2, -1 do
local j = math.random(i)
t[i], t[j] = t[j], t[i]
end
end
while issorted(balls) do shuffle(balls) end
print("RANDOM: "..table.concat(balls,","))
 
-- "2. Sort the balls in a way idiomatic to your language."
table.sort(balls, function(a, b) return order[a] < order[b] end)
 
-- "3. Check the sorted balls are in the order of the Dutch national flag."
print("SORTED: "..table.concat(balls,","))
print(issorted(balls) and "Properly sorted." or "IMPROPERLY SORTED!!")</syntaxhighlight>
{{out}}
<pre>RANDOM: white,white,blue,blue,red,red,blue,white,red,white
SORTED: red,red,red,white,white,white,white,blue,blue,blue
Properly sorted.</pre>
 
=={{header|M2000 Interpreter}}==
Most times the Three Way Partition makes more changed than the first algorithm. Also if the array is sorted from the start, no changes give the first algorithm and 23 changes the Three Way Partition,
 
<syntaxhighlight lang="m2000 interpreter">
Report "Dutch Flag from Dijkstra"
const center=2
enum balls {Red, White, Blue}
fillarray=lambda a=(Red, White, Blue) (size as long=10)-> {
if size<1 then size=1
randomitem=lambda a->a#val(random(0,2))
dim a(size)<<randomitem()
=a()
}
Display$=lambda$ (s as array) ->{
Document r$=eval$(array(s))
if len(s)>1 then
For i=1 to len(s)-1 {
r$=", "+eval$(array(s,i))
}
end if
=r$
}
TestSort$=lambda$ (s as array)-> {
="unsorted: "
x=array(s)
for i=1 to len(s)-1 {
k=array(s,i)
if x>k then break
swap x, k
}
="sorted: "
}
Positions=lambda mid=White (a as array) ->{
m=len(a)
dim Base 0, b(m)=-1
low=-1
high=m
m--
i=0
medpos=stack
link a to a()
for i=m to 0 {
if a(i)<=mid then exit
high--
b(high)=high
}
for i=0 to m {
if a(i)>=mid then exit
low++
b(low)=low
}
if high-low>1 then
for i=low+1 to high-1 {
select case a(i)<=>Mid
case -1
low++ : b(low)=i
case 1
{
high-- :b(high)=i
if High<i then swap b(high), b(i)
}
else case
stack medpos {data i}
end select
}
end if
if Len(medpos)>0 then
dim c()
c()=array(medpos)
stock c(0) keep len(c()), b(low+1)
for i=low+1 to high-1
if b(i)>low and b(i)<high and b(i)<>i then swap b(b(i)), b(i)
next i
end if
if low>0 then
for i=0 to low
if b(i)<=low and b(i)<>i then swap b(b(i)), b(i)
next
end if
if High<m then
for i=m to High
if b(i)>=High and b(i)<>i then swap b(b(i)), b(i)
next
end if
=b()
}
InPlace=Lambda (&p(), &Final()) ->{
def i=0, j=-1, k=-1, many=0
for i=0 to len(p())-1
if p(i)<>i then
j=i
z=final(j)
do
final(j)=final(p(j))
k=j
j=p(j)
p(k)=k
many++
until j=i
final(k)=z
end if
next
=many
}
 
 
Dim final(), p(), second(), p1()
Rem final()=(White,Red,Blue,White,Red, Red, Blue)
Rem final()=(white, blue, red, blue, white)
 
final()=fillarray(30)
Print "Items: ";len(final())
Report TestSort$(final())+Display$(final())
\\ backup for final() for second example
second()=final()
p()=positions(final())
\\ backup p() to p1() for second example
p1()=p()
 
 
Report Center, "InPlace"
rem Print p() ' show array items
many=InPlace(&p(), &final())
rem print p() ' show array items
Report TestSort$(final())+Display$(final())
print "changes: "; many
 
 
Report Center, "Using another array to make the changes"
final()=second()
\\ using a second array to place only the changes
item=each(p1())
many=0
While item {
if item^=array(item) else final(item^)=second(array(item)) : many++
}
Report TestSort$(final())+Display$(final())
print "changes: "; many
Module three_way_partition (A as array, mid as balls, &swaps) {
Def i, j, k
k=Len(A)
Link A to A()
While j < k
if A(j) < mid Then
Swap A(i), A(j)
swaps++
i++
j++
Else.if A(j) > mid Then
k--
Swap A(j), A(k)
swaps++
Else
j++
End if
End While
}
Many=0
Z=second()
Print
Report center, {Three Way Partition
}
Report TestSort$(Z)+Display$(Z)
three_way_partition Z, White, &many
Print
Report TestSort$(Z)+Display$(Z)
Print "changes: "; many
 
</syntaxhighlight>
 
{{out}}
<pre>
Dutch Flag from Dijkstra
Items: 30
unsorted: Red, White, White, Red, Red, White, Blue, Red, Red, Blue, Red, Blue, White, White, Red, White, Blue, Blue, White, Blue, Red, Blue, Blue, White, Blue, White, Blue, Red, White, White
InPlace
sorted: Red, Red, Red, Red, Red, Red, Red, Red, Red, White, White, White, White, White, White, White, White, White, White, White, Blue, Blue, Blue, Blue, Blue, Blue, Blue, Blue, Blue, Blue
changes: 20
Using another array to make the changes
sorted: Red, Red, Red, Red, Red, Red, Red, Red, Red, White, White, White, White, White, White, White, White, White, White, White, Blue, Blue, Blue, Blue, Blue, Blue, Blue, Blue, Blue, Blue
changes: 20
Three Way Partition
unsorted: Red, White, White, Red, Red, White, Blue, Red, Red, Blue, Red, Blue, White, White, Red, White, Blue, Blue, White, Blue, Red, Blue, Blue, White, Blue, White, Blue, Red, White, White
sorted: Red, Red, Red, Red, Red, Red, Red, Red, Red, White, White, White, White, White, White, White, White, White, White, White, Blue, Blue, Blue, Blue, Blue, Blue, Blue, Blue, Blue, Blue
changes: 19
</pre>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">flagSort[data_List] := Sort[data, (#1 === RED || #2 === BLUE) &]</langsyntaxhighlight>
{{out}}
<pre>flagSort[{WHITE, RED, RED, WHITE, WHITE, BLUE, WHITE, BLUE, BLUE, WHITE, WHITE, BLUE}]
 
{RED, RED, WHITE, WHITE, WHITE, WHITE, WHITE, WHITE, BLUE, BLUE, BLUE, BLUE}</pre>
 
=={{header|Nim}}==
We have chosen to use the sorting algorithm proposed by Dijkstra. To switch from our solution to one using Nim sorting algorithm, one has to add “import algorithm” at the beginning and to replace the lines <code>var sortedColors = colors</code> and <code>threeWayPartition(sortedColors, White)</code> by the single line <code>let sortedColors = sorted(colors)</code>.
 
The number of colors may be specified as argument in the command line. By default, 10 colors are randomly chosen.
 
<syntaxhighlight lang="nim">import os, random, strutils
 
type Color {.pure.} = enum Red = "R", White = "W", Blue = "B"
 
#---------------------------------------------------------------------------------------------------
 
proc isSorted(a: openArray[Color]): bool =
# Check if an array of colors is in the order of the dutch national flag.
var prevColor = Red
for color in a:
if color < prevColor:
return false
prevColor = color
return true
 
#---------------------------------------------------------------------------------------------------
 
proc threeWayPartition(a: var openArray[Color]; mid: Color) =
## Dijkstra way to sort the colors.
var i, j = 0
var k = a.high
while j <= k:
if a[j] < mid:
swap a[i], a[j]
inc i
inc j
elif a[j] > mid:
swap a[j], a[k]
dec k
else:
inc j
 
#———————————————————————————————————————————————————————————————————————————————————————————————————
 
var n: Positive = 10
 
# Get the number of colors.
if paramCount() > 0:
try:
n = paramStr(1).parseInt()
if n <= 1:
raise newException(ValueError, "")
except ValueError:
echo "Wrong number of colors"
quit(QuitFailure)
 
# Create the colors.
randomize()
var colors = newSeqOfCap[Color](n)
 
while true:
for i in 0..<n:
colors.add(Color(rand(ord(Color.high))))
if not colors.isSorted():
break
colors.setLen(0) # Reset for next try.
 
echo "Original: ", colors.join("")
 
# Sort the colors.
var sortedColors = colors
threeWayPartition(sortedColors, White)
doAssert sortedColors.isSorted()
echo "Sorted: ", sortedColors.join("")</syntaxhighlight>
 
{{out}}
With 10 colors:
<pre>Original: WWWRBRWWBW
Sorted: RRWWWWWWBB</pre>
 
=={{header|PARI/GP}}==
A [[counting sort]] might be more appropriate here, but that would conceal the details of the sort.
<langsyntaxhighlight lang="parigp">compare(a,b)={
if (a==b,
0
Line 2,055 ⟶ 2,889:
while(inorder(v), v=r(10));
v=vecsort(v,compare);
inorder(v)</langsyntaxhighlight>
 
{{out}}
Line 2,062 ⟶ 2,896:
=={{header|Perl}}==
The task is probably not to just sort an array. The wikipedia links has a slightly better explanation that leads to the following code:
<langsyntaxhighlight lang="perl">use warnings;
use strict;
use 5.010; # //
Line 2,133 ⟶ 2,967:
 
show($balls);
are_ordered($balls) or die "Incorrect\n";</langsyntaxhighlight>
You can run it with no parameters, it sorts 10 balls in such a case. If you provide one parameter, it is used as the number of balls. The second parameter turns on debugging that shows how the balls are being swapped.
 
=={{header|Perl 6Phix}}==
Minimizes the number of read and swap operations, straight translation of the wikipedia pseudocode:
Here are five ways to do it, all one liners (apart from the test apparatus).
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang perl6>enum NL <red white blue>;
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
my @colors;
<span style="color: #008080;">function</span> <span style="color: #000000;">three_way_partition</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">mid</span><span style="color: #0000FF;">)</span>
 
<span style="color: #004080;">integer</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
sub how'bout (&this-way) {
<span style="color: #008080;">while</span> <span style="color: #000000;">j</span> <span style="color: #0000FF;"><=</span> <span style="color: #000000;">n</span> <span style="color: #008080;">do</span>
sub show {
<span style="color: #008080;">if</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;"><</span> <span style="color: #000000;">mid</span> <span style="color: #008080;">then</span>
say @colors;
<span style="color: #0000FF;">{</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]}</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">],</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]}</span>
say "Ordered: ", [<=] @colors;
<span style="color: #000000;">i</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
}
<span style="color: #000000;">j</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
 
<span style="color: #008080;">elsif</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">></span> <span style="color: #000000;">mid</span> <span style="color: #008080;">then</span>
@colors = NL.roll(20);
<span style="color: #0000FF;">{</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">],</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">n</span><span style="color: #0000FF;">]}</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">n</span><span style="color: #0000FF;">],</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]}</span>
show;
<span style="color: #000000;">n</span> <span style="color: #0000FF;">-=</span> <span style="color: #000000;">1</span>
this-way;
<span style="color: #008080;">else</span>
show;
<span style="color: #000000;">j</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
say '';
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
}
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
 
<span style="color: #008080;">return</span> <span style="color: #000000;">s</span>
say "Using functional sort";
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
how'bout { @colors = sort *.value, @colors }
 
<span style="color: #008080;">constant</span> <span style="color: #000000;">colours</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"red"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"white"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"blue"</span><span style="color: #0000FF;">}</span>
say "Using in-place sort";
<span style="color: #008080;">enum</span> <span style="color: #000080;font-style:italic;">/*red,*/</span> <span style="color: #000000;">white</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">blue</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">maxc</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">blue</span>
how'bout { @colors .= sort: *.value }
 
<span style="color: #008080;">procedure</span> <span style="color: #000000;">show</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">msg</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
say "Using a Bag";
<span style="color: #004080;">sequence</span> <span style="color: #000000;">t</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">))</span>
how'bout { @colors = flat red, white, blue Zxx bag(@colors».key)<red white blue> }
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
 
<span style="color: #000000;">t</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">colours</span><span style="color: #0000FF;">[</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]]</span>
say "Using the classify method";
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
how'bout { @colors = flat (.list for %(@colors.classify: *.value){0,1,2}) }
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s: %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">msg</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t</span><span style="color: #0000FF;">)})</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
say "Using multiple greps";
how'bout { @colors = flat (.grep(red), .grep(white), .grep(blue) given @colors) }</lang>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">unsorted</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">sorted</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">unsorted</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sq_rand</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">maxc</span><span style="color: #0000FF;">,</span><span style="color: #000000;">12</span><span style="color: #0000FF;">))</span>
<span style="color: #000080;font-style:italic;">-- sorted = sort(deep_copy(unsorted)) -- (works just as well)</span>
<span style="color: #000000;">sorted</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">three_way_partition</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">deep_copy</span><span style="color: #0000FF;">(</span><span style="color: #000000;">unsorted</span><span style="color: #0000FF;">),</span> <span style="color: #000000;">white</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">unsorted</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">sorted</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #0000FF;">?</span><span style="color: #008000;">"oops"</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #000000;">show</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Unsorted"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">unsorted</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">show</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Sorted"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">sorted</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
<small>I thought of unsorted=shuffle(unsorted) in the "oops" loop, but of course that'd repeat forever should they all be the same colour.</small>
{{out}}
<pre>
<pre>Using functional sort
redUnsorted: redblue whiteblue whiteblue redblue red red red red red redwhite white red white red red red white white whiteblue
Sorted: red red red white white white white blue blue blue blue blue
Ordered: False
</pre>
red red red red red red red red red red red red red white white white white white white white
Ordered: True
 
=={{header|Picat}}==
Using in-place sort
<syntaxhighlight lang="picat">go =>
red blue white red white blue white blue red white blue blue blue red white white red blue red blue
_ = random2(), % random seed
Ordered: False
N = 21,
red red red red red red white white white white white white blue blue blue blue blue blue blue blue
Map = new_map([1=red,2=white,3=blue]),
Ordered: True
[Rand,Sorted] = dutch_random_sort(N,Map,Map.inverse()),
println('rand '=Rand),
println(sorted=Sorted),
nl.
 
% generate a random order and ensure it's not already dutch sorted
Using a Bag
dutch_random_sort(N,Map,MapInv) = [Rand,Sorted] =>
red blue blue blue white red white red white blue blue red red red red blue blue red white blue
Rand = dutch_random1(N,Map),
Ordered: False
Sorted = dutch_sort(Rand,MapInv),
red red red red red red red red white white white white blue blue blue blue blue blue blue blue
while (Rand == Sorted)
Ordered: True
println("Randomize again"),
Rand := dutch_random1(N,Map),
Sorted := dutch_sort(Rand,MapInv)
end.
 
dutch_random1(N,Map) = [Map.get(1+(random() mod Map.map_to_list().length)) : _I in 1..N].
Using the classify method
blue red white blue blue white white red blue red red white red blue white white red blue red white
Ordered: False
red red red red red red red white white white white white white white blue blue blue blue blue blue
Ordered: True
 
dutch_sort(L,MapInv) = [R : _=R in [MapInv.get(R)=R : R in L].sort()].
Using multiple greps
red white blue white white red blue white red white red white white white white white red red blue red
Ordered: False
red red red red red red red white white white white white white white white white white blue blue blue
Ordered: True</pre>
 
inverse(Map) = new_map([V=K : K=V in Map]).</syntaxhighlight>
=={{header|Phix}}==
Minimizes the number of read and swap operations, straight translation of the wikipedia pseudocode:
<lang Phix>function three_way_partition(sequence s, integer mid)
integer i=1, j=1, n = length(s)
 
while j < n do
if s[j] < mid then
{s[i],s[j]} = {s[j],s[i]}
i += 1
j += 1
elsif s[j] > mid then
{s[j],s[n]} = {s[n],s[j]}
n -= 1
else
j += 1
end if
end while
return s
end function
 
constant colours = {"red","white","blue"}
enum /*red,*/ white = 2, blue, maxc = blue
 
procedure show(string msg, sequence s)
for i=1 to length(s) do
s[i] = colours[s[i]]
end for
printf(1,"%s: %s\n",{msg,join(s)})
end procedure
 
sequence unsorted, sorted
while 1 do
unsorted = sq_rand(repeat(maxc,12))
-- sorted = sort(unsorted) -- (works just as well)
sorted = three_way_partition(unsorted, white)
if unsorted!=sorted then exit end if
?"oops"
end while
show("Unsorted",unsorted)
show("Sorted",sorted)</lang>
<small>I thought of unsorted=shuffle(unsorted) in the "oops" loop, but of course that'd repeat forever should they all be the same colour.</small>
{{out}}
<pre>rand = [red,blue,white,white,white,blue,blue,blue,red,red,blue,white,blue,blue,red,white,blue,blue,white,white,red]
<pre>
sorted = [red,red,red,red,red,white,white,white,white,white,white,white,blue,blue,blue,blue,blue,blue,blue,blue,blue]</pre>
Unsorted: blue blue blue blue red white white red white red white blue
Sorted: red red red white white white white blue blue blue blue blue
</pre>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(def 'Colors
(list
(def 'RED 1)
Line 2,259 ⟶ 3,063:
(prin "Sorted balls ")
(print S)
(prinl " are sorted") )</langsyntaxhighlight>
{{out}}
<pre>Original balls (RED BLUE WHITE BLUE BLUE RED WHITE WHITE WHITE) not sorted
Line 2,266 ⟶ 3,070:
=={{header|PowerShell}}==
{{works with|PowerShell|2}}
<syntaxhighlight lang="powershell">
<lang PowerShell>
$Colors = 'red', 'white','blue'
Line 2,283 ⟶ 3,087:
''
$SortedBalls
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,312 ⟶ 3,116:
Works with SWI-Prolog 6.1.11
===Prolog spirit===
<langsyntaxhighlight Prologlang="prolog">dutch_flag(N) :-
length(L, N),
repeat,
Line 2,371 ⟶ 3,175:
 
is_dutch_flag_blue([]).
</syntaxhighlight>
</lang>
{{out}}
<pre> ?- dutch_flag(20).
Line 2,384 ⟶ 3,188:
===Functional spirit===
Use of filters.
<langsyntaxhighlight Prologlang="prolog">dutch_flag(N) :-
length(L, N),
 
Line 2,446 ⟶ 3,250:
 
is_dutch_flag_blue([]).
</syntaxhighlight>
</lang>
 
=={{header|Python}}==
===Python: Sorted===
The heart of the idiomatic Dutch sort in python is the call to function <code>sorted</code> in function <code>dutch_flag_sort</code>.
<langsyntaxhighlight lang="python">import random
 
colours_in_order = 'Red White Blue'.split()
Line 2,485 ⟶ 3,289:
 
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{out|Sample output}}
<pre>Original Ball order: ['Red', 'Red', 'Blue', 'Blue', 'Blue', 'Red', 'Red', 'Red', 'White', 'Blue']
Line 2,495 ⟶ 3,299:
 
Replace the function/function call dutch_flag_sort above, with dutch_flag_sort2 defined as:
<langsyntaxhighlight lang="python">from itertools import chain
def dutch_flag_sort2(items, order=colours_in_order):
'return summed filter of items using the given order'
return list(chain.from_iterable(filter(lambda c: c==colour, items)
for colour in order))</langsyntaxhighlight>
 
Or equivalently using a list comprehension (though perhaps less clear):
<langsyntaxhighlight lang="python">def dutch_flag_sort2(items, order=colours_in_order):
'return summed filter of items using the given order'
return [c for colour in order for c in items if c==colour]</langsyntaxhighlight>
Output follows that of the sorting solution above.
 
Line 2,511 ⟶ 3,315:
 
Replace the function/function call dutch_flag_sort above, with dutch_flag_sort3 defined as:
<langsyntaxhighlight lang="python">def dutch_flag_sort3(items, order=colours_in_order):
'counts each colour to construct flag'
return sum([[colour] * items.count(colour) for colour in order], [])</langsyntaxhighlight>
Output follows that of the sorting solution above.
 
===Python: Explicit in-place sort===
<langsyntaxhighlight lang="python">import random
 
colours_in_order = 'Red White Blue'.split()
Line 2,566 ⟶ 3,370:
 
if __name__ == '__main__':
main()</langsyntaxhighlight>
Output follows that of the sorting solution above.
 
=={{header|Racket}}==
 
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
 
Line 2,607 ⟶ 3,411:
balls sorted (if (dutch-order? sorted) 'OK 'BAD)))
(for-each test (list sort-balls/key sort-balls/compare))
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,620 ⟶ 3,424:
==> OK
</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
Here are five ways to do it, all one liners (apart from the test apparatus).
<syntaxhighlight lang="raku" line>enum NL <red white blue>;
my @colors;
 
sub how'bout (&this-way) {
sub show {
say @colors;
say "Ordered: ", [<=] @colors;
}
 
@colors = NL.roll(20);
show;
this-way;
show;
say '';
}
 
say "Using functional sort";
how'bout { @colors = sort *.value, @colors }
 
say "Using in-place sort";
how'bout { @colors .= sort: *.value }
 
say "Using a Bag";
how'bout { @colors = flat red, white, blue Zxx bag(@colors».key)<red white blue> }
 
say "Using the classify method";
how'bout { @colors = flat (.list for %(@colors.classify: *.value){0,1,2}) }
 
say "Using multiple greps";
how'bout { @colors = flat (.grep(red), .grep(white), .grep(blue) given @colors) }</syntaxhighlight>
{{out}}
<pre>Using functional sort
red red white white red red red red red red red white red white red red red white white white
Ordered: False
red red red red red red red red red red red red red white white white white white white white
Ordered: True
 
Using in-place sort
red blue white red white blue white blue red white blue blue blue red white white red blue red blue
Ordered: False
red red red red red red white white white white white white blue blue blue blue blue blue blue blue
Ordered: True
 
Using a Bag
red blue blue blue white red white red white blue blue red red red red blue blue red white blue
Ordered: False
red red red red red red red red white white white white blue blue blue blue blue blue blue blue
Ordered: True
 
Using the classify method
blue red white blue blue white white red blue red red white red blue white white red blue red white
Ordered: False
red red red red red red red white white white white white white white blue blue blue blue blue blue
Ordered: True
 
Using multiple greps
red white blue white white red blue white red white red white white white white white red red blue red
Ordered: False
red red red red red red red white white white white white white white white white white blue blue blue
Ordered: True</pre>
 
=={{header|REXX}}==
Line 2,627 ⟶ 3,495:
The REXX solution could've been simplified somewhat by the use of the &nbsp; '''countstr''' &nbsp; BIF &nbsp; (but some older REXX interpreters don't have).
 
<langsyntaxhighlight lang="rexx">/*REXX program reorders a set of random colored balls into a correct order, which is the*/
/*────────────────────────────────── order of colors on the Dutch flag: red white blue.*/
parse arg N colors /*obtain optional arguments from the CL*/
Line 2,658 ⟶ 3,526:
/*──────────────────────────────────────────────────────────────────────────────────────*/
countWords: procedure; parse arg ?,hay; s=1
do r=0 until _==0; _=wordpos(?, hay, s); s=_+1; end /*r*/; return r</langsyntaxhighlight>
'''output''' &nbsp; when using the default input:
<pre>
Line 2,675 ⟶ 3,543:
 
===colors (as letters)===
<langsyntaxhighlight lang="rexx">/*REXX program reorders a set of random colored balls into a correct order, which is the*/
/*────────────────────────────────── order of colors on the Dutch flag: red white blue.*/
parse arg N colors /*obtain optional arguments from the CL*/
Line 2,703 ⟶ 3,571:
say
say 'The sorted colored ball list has been confirmed as being sorted correctly.'
exit /*stick a fork in it, we're all done. */</langsyntaxhighlight>
'''output''' &nbsp; when using the default input:
<pre>
Line 2,718 ⟶ 3,586:
 
</pre>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Dutch national flag problem
 
Line 2,742 ⟶ 3,611:
next
next
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,750 ⟶ 3,619:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">class Ball
FLAG = {red: 1, white: 2, blue: 3}
Line 2,775 ⟶ 3,644:
puts "Random: #{balls}"
puts "Sorted: #{balls.sort}"
</langsyntaxhighlight>
{{out}}
<pre>Random: [blue, red, red, red, blue, blue, white, red]
Line 2,782 ⟶ 3,651:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">flag$ = "Red,White,Blue"
 
print "Random: |";
Line 2,799 ⟶ 3,668:
end if
next j
next i</langsyntaxhighlight>
<pre>Random: |White |Blue |White |Red |Red |White |Red |Blue |Red |White |
Sorted: |Red |Red |Red |Red |White |White |White |White |Blue |Blue |</pre>
Line 2,805 ⟶ 3,674:
=={{header|Rust}}==
{{libheader|rand}}
<langsyntaxhighlight lang="rust">extern crate rand;
 
use rand::Rng;
Line 2,848 ⟶ 3,717:
println!("Oops, did not sort colors correctly!");
}
}</langsyntaxhighlight>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">object FlagColor extends Enumeration {
type FlagColor = Value
val Red, White, Blue = Value
Line 2,861 ⟶ 3,730:
 
println(s"Generated balls (${genBalls mkString " "}) are $sorted.")
println(s"Sorted balls (${sortedBalls mkString " "}) are sorted.")</langsyntaxhighlight>
 
{{out}}
<pre>Generated balls (Blue Blue Blue White Blue Blue Red Red Blue White) are not sorted.
Sorted balls (Red Red White White Blue Blue Blue Blue Blue Blue) are sorted.</pre>
 
=={{header|sed}}==
The first part of the task is skipped, as there is no possibility to create random data within ''sed'' itself.
<syntaxhighlight lang="sed">:la
s/\(WW*\)\([RB].*\)/\2\1/
t la
:lb
s/\(BB*\)\([RW].*\)/\2\1/
t lb
/^RR*WW*BB*$/!d</syntaxhighlight>
{{out}}
<pre>
$ echo WRRWRRRBBWBRRWBWWB | sed -f dutch_flag_sort.sed
RRRRRRRWWWWWWBBBBB
</pre>
 
=={{header|SQL}}==
<langsyntaxhighlight SQLlang="sql">-- Create and populate tables
create table colours (id integer primary key, name varchar(5));
insert into colours (id, name) values ( 1, 'red' );
Line 2,902 ⟶ 3,786:
-- Tidy up
drop table balls;
drop table colours;</langsyntaxhighlight>
{{out}}
<pre>COLOUR
Line 2,929 ⟶ 3,813:
# ''Sort the balls in a way idiomatic to your language.'' Yup!
# ''Check the sorted balls are in the order of the Dutch national flag.'' Not checked beyond eyeballing - is there a db implementation that gets <tt>order by</tt> wrong??
 
=={{header|Swift}}==
<syntaxhighlight lang="swift">// Algorithm from https://en.wikipedia.org/wiki/Dutch_national_flag_problem
func partition3<T: Comparable>(_ a: inout [T], mid: T) {
var i = 0
var j = 0
var k = a.count - 1
while j <= k {
if a[j] < mid {
a.swapAt(i, j);
i += 1;
j += 1;
} else if a[j] > mid {
a.swapAt(j, k);
k -= 1;
} else {
j += 1;
}
}
}
 
func isSorted<T: Comparable>(_ a: [T]) -> Bool {
var i = 0
let n = a.count
while i + 1 < n {
if a[i] > a[i + 1] {
return false
}
i += 1
}
return true
}
 
enum Ball : CustomStringConvertible, Comparable {
case red
case white
case blue
var description : String {
switch self {
case .red: return "red"
case .white: return "white"
case .blue: return "blue"
}
}
}
 
var balls: [Ball] = [ Ball.red, Ball.white, Ball.blue,
Ball.red, Ball.white, Ball.blue,
Ball.red, Ball.white, Ball.blue]
balls.shuffle()
print("\(balls)")
print("Sorted: \(isSorted(balls))")
 
partition3(&balls, mid: Ball.white)
print("\(balls)")
print("Sorted: \(isSorted(balls))")</syntaxhighlight>
 
{{out}}
<pre>
[white, blue, red, red, white, blue, red, blue, white]
Sorted: false
[red, red, red, white, white, white, blue, blue, blue]
Sorted: true
</pre>
 
=={{header|Tcl}}==
This isn't very efficient in terms of the sorting itself (and it happens to use <code>lsearch</code> twice in the comparator!) but it is very simple to write like this.
<langsyntaxhighlight lang="tcl"># The comparison function
proc dutchflagcompare {a b} {
set colors {red white blue}
Line 2,961 ⟶ 3,910:
} else {
puts "sort failed\n$sorted"
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,967 ⟶ 3,916:
red red red red red red red white white white white white white white white white blue blue blue blue
</pre>
 
=={{header|uBasic/4tH}}==
This version is based on Edsger Dijkstra's original algorithm. The flag may come out a bit shredded , but it has been assembled the correct way.
<syntaxhighlight lang="text">s = 100
 
For x = 0 To s-1
@(x) = Rnd(3)
Next
' Edsger Dijkstra algorithm starts here
i = 0
j = 0
k = s-1
Do
While j < k+1
If @(j) = 0 Then ' case "red"
Push @(j) : @(j) = @(i) : @(i) = Pop()
i = i + 1 ' fairly efficient exchange
j = j + 1
Else If @(j) = 2 Then ' case "blue"
Push @(j) : @(j) = @(k) : @(k) = Pop()
k = k - 1 ' fairly efficient exchange
Else ' you'd expect case "white" here
j = j + 1
Endif Endif
Loop
' end of Dijkstra's algorithm
n = 0
 
For x = 0 To s-1 ' now show the whole shebang
If @(x) # n Then Print : n = @(x)
Print Chr(Peek ("RWB", @(x)));
Next
 
Print</syntaxhighlight>
{{Out}}
<pre>RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR
WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW
BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB
 
0 OK, 0:858</pre>
 
=={{header|UNIX Shell}}==
{{works with|Bash}}
<langsyntaxhighlight lang="bash">COLORS=(red white blue)
 
# to go from name to number, we make variables out of the color names
Line 3,027 ⟶ 4,017:
done
echo "${a[@]}"
}</langsyntaxhighlight>
 
Test code:
<langsyntaxhighlight lang="bash">declare -i len=${1:-10}
balls=()
while (( ${#balls[@]} < len )) || dutch? "${balls[@]}"; do
Line 3,037 ⟶ 4,027:
echo "Initial list: ${balls[@]}"
balls=($(dutch "${balls[@]}"))
echo "Sorted: ${balls[@]}"</langsyntaxhighlight>
 
{{out}}
Line 3,044 ⟶ 4,034:
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
'Solution derived from http://www.geeksforgeeks.org/sort-an-array-of-0s-1s-and-2s/.
 
Line 3,089 ⟶ 4,079:
WScript.StdOut.Write "Sorted: " & sort(unsort)
WScript.StdOut.WriteLine
</syntaxhighlight>
</lang>
 
{{Out}}
Line 3,099 ⟶ 4,089:
=={{header|Visual FoxPro}}==
===SQL Version===
<langsyntaxhighlight lang="vfp">
CLOSE DATABASES ALL
LOCAL lcCollate As String, i As Integer, n As Integer
Line 3,134 ⟶ 4,124:
RETURN INT(3*RAND()) + 1
ENDFUNC
</syntaxhighlight>
</lang>
===Array Version===
<langsyntaxhighlight lang="vfp">
LOCAL i As Integer, n As Integer, colours As String, k As Integer
colours = "Red,White,Blue"
Line 3,172 ⟶ 4,162:
RETURN INT(3*RAND()) + 1
ENDFUNC
</syntaxhighlight>
</lang>
 
=={{header|Wren}}==
{{libheader|Wren-sort}}
<syntaxhighlight lang="wren">import "random" for Random
import "./sort" for Sort
 
var colors = ["Red", "White", "Blue"]
var colorMap = { "Red": 0, "White": 1, "Blue": 2 }
var colorCmp = Fn.new { |c1, c2| (colorMap[c1] - colorMap[c2]).sign }
var NUM_BALLS = 9
var r = Random.new()
var balls = List.filled(NUM_BALLS, colors[0])
 
while (true) {
for (i in 0...NUM_BALLS) balls[i] = colors[r.int(3)]
if (!Sort.isSorted(balls, colorCmp)) break
}
 
System.print("Before sorting : %(balls)")
Sort.insertion(balls, colorCmp)
System.print("After sorting : %(balls)")</syntaxhighlight>
 
{{out}}
Sample run:
<pre>
Before sorting : [Blue, Blue, White, Blue, White, Blue, Red, White, White]
After sorting : [Red, White, White, White, White, Blue, Blue, Blue, Blue]
</pre>
 
=={{header|XPL0}}==
<syntaxhighlight lang "XPL0">
def Red, White, Blue;
def Size = 10;
int A(Size), N;
 
proc ShowOrder;
[for N:= 0 to Size-1 do
case A(N) of
Red: Text(0, "Red ");
Blue: Text(0, "Blue ")
other Text(0, "White ");
CrLf(0);
];
 
proc Part3Ways; \Partition array A three ways (code from Wikipedia)
def Mid = White;
int I, J, K, T;
[I:= 0; J:= 0; K:= Size-1;
while J <= K do
if A(J) < Mid then
[T:= A(I); A(I):= A(J); A(J):= T;
I:= I+1;
J:= J+1;
]
else if A(J) > Mid then
[T:= A(J); A(J):= A(K); A(K):= T;
K:= K-1;
]
else J:= J+1;
];
 
[for N:= 0 to Size-1 do A(N):= Ran(3);
Text(0, "Original order : ");
ShowOrder;
Part3Ways;
Text(0, "Sorted order : ");
ShowOrder;
]</syntaxhighlight>
{{out}}
<pre>
Original order : Red Red Blue Blue White Red Red White Blue Red
Sorted order : Red Red Red Red Red White White Blue Blue Blue
</pre>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">const RED=0, WHITE=1, BLUE=2; var BALLS=T(RED,WHITE,BLUE);
fcn colorBalls(balls){ balls.apply(T("red","white","blue").get).concat(", "); }
 
Line 3,184 ⟶ 4,247:
}while(balls==sortedBalls); // make sure sort does something
println("Original ball order:\n", colorBalls(balls));
println("\nSorted ball order:\n", colorBalls(sortedBalls));</langsyntaxhighlight>
{{out}}
<pre>
Line 3,196 ⟶ 4,259:
=={{header|ZX Spectrum Basic}}==
{{trans|Run_BASIC}}
<langsyntaxhighlight lang="zxbasic">10 LET r$="Red": LET w$="White": LET b$="Blue"
20 LET c$="RWB"
30 DIM b(10)
Line 3,209 ⟶ 4,272:
120 IF b(j)=i THEN PRINT VAL$ (c$(i)+"$");" ";
130 NEXT j
140 NEXT i</langsyntaxhighlight>
1,979

edits