Created
December 11, 2017 14:54
-
-
Save remcopeereboom/2cbe61ba46e62b9c833f9b6b487ab428 to your computer and use it in GitHub Desktop.
A solution to the Dutch flag problem.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def color(a, i) | |
a[i] | |
end | |
def swap(a, i, j) | |
a[i], a[j] = a[j], a[i] | |
end | |
def flag_sort(a) | |
# Indices (not colors): | |
l = 0 | |
m = 0 | |
r = a.size - 1 | |
while m <= r | |
case color(a, m) | |
when :red | |
swap(a, l, m) | |
l += 1 | |
m += 1 | |
when :white | |
m += 1 | |
when :blue | |
swap(a, m, r) | |
r -= 1 | |
else | |
fail "Wrong pebble color!" | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment