-
Notifications
You must be signed in to change notification settings - Fork 72
/
cocktail_shaker_sort.rs
61 lines (49 loc) · 1.14 KB
/
cocktail_shaker_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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
use crate::sorting::traits::Sorter;
fn cocktail_shaker_sort<T: Ord>(arr: &mut [T]) {
let len = arr.len();
if len == 0 {
return;
}
loop {
let mut swapped = false;
for i in 0..(len - 1).clamp(0, len) {
if arr[i] > arr[i + 1] {
arr.swap(i, i + 1);
swapped = true;
}
}
if !swapped {
break;
}
swapped = false;
for i in (0..(len - 1).clamp(0, len)).rev() {
if arr[i] > arr[i + 1] {
arr.swap(i, i + 1);
swapped = true;
}
}
if !swapped {
break;
}
}
}
pub struct CocktailShakerSort;
impl<T> Sorter<T> for CocktailShakerSort
where
T: Ord + Copy,
{
fn sort_inplace(arr: &mut [T]) {
cocktail_shaker_sort(arr);
}
}
#[cfg(test)]
mod tests {
use crate::sorting::traits::Sorter;
use crate::sorting::CocktailShakerSort;
sorting_tests!(CocktailShakerSort::sort, cocktail_shaker_sort);
sorting_tests!(
CocktailShakerSort::sort_inplace,
cocktail_shaker_sort,
inplace
);
}