|
| 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 | +} |
0 commit comments