forked from TheAlgorithms/Rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cocktail_shaker_sort.rs
68 lines (56 loc) · 1.32 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
62
63
64
65
66
67
68
pub 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;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn basic() {
let mut arr = vec![5, 2, 1, 3, 4, 6];
cocktail_shaker_sort(&mut arr);
assert_eq!(arr, vec![1, 2, 3, 4, 5, 6]);
}
#[test]
fn empty() {
let mut arr = Vec::<i32>::new();
cocktail_shaker_sort(&mut arr);
assert_eq!(arr, vec![]);
}
#[test]
fn one_element() {
let mut arr = vec![1];
cocktail_shaker_sort(&mut arr);
assert_eq!(arr, vec![1]);
}
#[test]
fn pre_sorted() {
let mut arr = vec![1, 2, 3, 4, 5, 6];
cocktail_shaker_sort(&mut arr);
assert_eq!(arr, vec![1, 2, 3, 4, 5, 6]);
}
}