sorting_algorithm/cocktail_shaker_sort.rs
1/// Sorts a data set using Cocktail Shaker Sort
2///
3/// Average time complexity: O(n<sup>2</sup>)
4///
5/// # Examples
6///
7/// ```
8/// use sorting_algorithm::cocktail_shaker_sort;
9///
10/// fn main() {
11/// let mut data = [3, 1, 2, 5, 4];
12///
13/// cocktail_shaker_sort::sort(&mut data);
14///
15/// assert_eq!(data, [1, 2, 3, 4, 5]);
16/// }
17/// ```
18pub fn sort<T: Ord>(data: &mut [T]) {
19 if data.len() <= 1 {
20 return;
21 }
22
23 let mut low = 0;
24 let mut high = data.len() - 1;
25
26 while low < high {
27 let mut swapped = false;
28
29 for i in low..high {
30 if data[i] > data[i + 1] {
31 data.swap(i, i + 1);
32 swapped = true;
33 }
34 }
35 high -= 1;
36
37 if !swapped {
38 return;
39 }
40
41 for i in (low..high).rev() {
42 if data[i] > data[i + 1] {
43 data.swap(i, i + 1);
44 swapped = true;
45 }
46 }
47 low += 1;
48
49 if !swapped {
50 return;
51 }
52 }
53}