Skip to content

Commit a2d96e0

Browse files
authored
Add Dutch National Flag Sort (rust-lang#401)
1 parent fbc20a7 commit a2d96e0

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
/*
2+
A Rust implementation of the Dutch National Flag sorting algorithm.
3+
4+
Reference implementation: https://github.com/TheAlgorithms/Python/blob/master/sorts/dutch_national_flag_sort.py
5+
More info: https://en.wikipedia.org/wiki/Dutch_national_flag_problem
6+
*/
7+
8+
#[derive(PartialOrd, PartialEq, Eq)]
9+
pub enum Colors {
10+
Red, // \
11+
White, // | Define the three colors of the Dutch Flag: 🇳🇱
12+
Blue, // /
13+
}
14+
use Colors::*;
15+
16+
// Algorithm implementation
17+
pub fn dutch_national_flag_sort(mut sequence: Vec<Colors>) -> Vec<Colors> {
18+
// We take ownership of `sequence` because the original `sequence` will be modified and then returned
19+
let length = sequence.len();
20+
if length <= 1 {
21+
return sequence; // Arrays of length 0 or 1 are automatically sorted
22+
}
23+
let mut low = 0;
24+
let mut mid = 0;
25+
let mut high = length - 1;
26+
while mid <= high {
27+
if sequence[mid] == Red {
28+
sequence.swap(low, mid);
29+
low += 1;
30+
mid += 1;
31+
} else if sequence[mid] == White {
32+
mid += 1;
33+
} else {
34+
// Equivalent to `else if sequence[mid] == Blue`,
35+
// because `Red`, `White`, and `Blue` are the only members of the Colors enum
36+
sequence.swap(mid, high);
37+
high -= 1;
38+
}
39+
}
40+
sequence
41+
}
42+
43+
#[cfg(test)]
44+
mod tests {
45+
use super::super::is_sorted;
46+
use super::*;
47+
48+
#[test]
49+
fn random_array() {
50+
let arr = vec![
51+
Red, Blue, White, White, Blue, Blue, Red, Red, White, Blue, White, Red, White, Blue,
52+
];
53+
let arr = dutch_national_flag_sort(arr);
54+
assert!(is_sorted(&arr))
55+
}
56+
57+
#[test]
58+
fn sorted_array() {
59+
let arr = vec![
60+
Red, Red, Red, Red, Red, White, White, White, White, White, Blue, Blue, Blue, Blue,
61+
];
62+
let arr = dutch_national_flag_sort(arr);
63+
assert!(is_sorted(&arr))
64+
}
65+
}

src/sorting/mod.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ mod cocktail_shaker_sort;
55
mod comb_sort;
66
mod counting_sort;
77
mod cycle_sort;
8+
mod dutch_national_flag_sort;
89
mod exchange_sort;
910
mod gnome_sort;
1011
mod heap_sort;
@@ -29,6 +30,7 @@ pub use self::comb_sort::comb_sort;
2930
pub use self::counting_sort::counting_sort;
3031
pub use self::counting_sort::generic_counting_sort;
3132
pub use self::cycle_sort::cycle_sort;
33+
pub use self::dutch_national_flag_sort::dutch_national_flag_sort;
3234
pub use self::exchange_sort::exchange_sort;
3335
pub use self::gnome_sort::gnome_sort;
3436
pub use self::heap_sort::heap_sort;

0 commit comments

Comments
 (0)