-
Notifications
You must be signed in to change notification settings - Fork 72
/
odd_even_sort.rs
47 lines (39 loc) · 965 Bytes
/
odd_even_sort.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
use crate::sorting::traits::Sorter;
fn odd_even_sort<T: Ord>(arr: &mut [T]) {
let len = arr.len();
if len == 0 {
return;
}
let mut sorted = false;
while !sorted {
sorted = true;
for i in (1..len - 1).step_by(2) {
if arr[i] > arr[i + 1] {
arr.swap(i, i + 1);
sorted = false;
}
}
for i in (0..len - 1).step_by(2) {
if arr[i] > arr[i + 1] {
arr.swap(i, i + 1);
sorted = false;
}
}
}
}
pub struct OddEvenSort;
impl<T> Sorter<T> for OddEvenSort
where
T: Ord + Copy,
{
fn sort_inplace(array: &mut [T]) {
odd_even_sort(array);
}
}
#[cfg(test)]
mod tests {
use crate::sorting::traits::Sorter;
use crate::sorting::OddEvenSort;
sorting_tests!(OddEvenSort::sort, odd_even_sort);
sorting_tests!(OddEvenSort::sort_inplace, odd_even_sort, inplace);
}