Sort Colors With Dutch Flag Partition
Partition a slice of 0s, 1s, and 2s with the dutch flag scheme: low, mid, and high indexes swap in place until every region is sorted in one pass.
Code
fn sort_colors(colors: &mut [u8]) {
// sort colors with a dutch flag partition: low/mid/high carve three regions
let mut low = 0;
let mut mid = 0;
let mut high = colors.len() - 1;
while mid <= high {
match colors[mid] {
0 => {
colors.swap(low, mid);
low += 1;
mid += 1;
}
1 => mid += 1,
_ => {
colors.swap(mid, high);
high -= 1;
}
}
}
}
fn main() {
let mut colors = [2u8, 0, 2, 1, 1, 0];
sort_colors(&mut colors);
println!("{colors:?}");
let mut already = [0u8, 1, 2];
sort_colors(&mut already);
println!("{already:?}");
}Sort Colors With Dutch Flag Partition: the mechanics
Under the hood: the functions sort_colors and main.
The loop while mid <= high is the only repeated construct. Pattern matching via match forces each shape of the value to be handled.
Watch out for
- No dependency resolution — the toolchain on its own is enough.
Using it
Entry signature: fn sort_colors(colors: &mut [u8])
The entry point wires sort_colors together — run it once and the whole demo flows.
Key statements
match colors[mid] {
0 => {
colors.swap(low, mid);
low += 1;
mid += 1;
}
1 => mid += 1,
_ => {
colors.swap(mid, high);
high -= 1;
}
}
Interactive Tools for This Topic
Line SorterSort text lines ascending or descending with numeric-aware ordering, duplicate removal, empty-line filtering, and locale-aware comparison.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- How do you run Sort Colors With Dutch Flag Partition?
- Nothing to install first — run the file and the program does the rest.
Report a problem with this exampleOpens a pre-filled issue on GitHub.