MCPcopy Create free account
hub / github.com/douchuan/algorithm / sort_cocktail

Function sort_cocktail

src/sort/selection.rs:28–55  ·  view source on GitHub ↗

鸡尾酒排序 (Cock-tail sort) 每次扫描可以同时查找最小值和最大值,将最小值放到开头, 最大值放到末尾

(a: &mut [T])

Source from the content-addressed store, hash-verified

26/// 每次扫描可以同时查找最小值和最大值,将最小值放到开头,
27/// 最大值放到末尾
28pub fn sort_cocktail<T>(a: &mut [T])
29where
30 T: Ord,
31{
32 let n = a.len();
33 let semi_n = n / 2;
34 // 注意右边界是semi_n
35 // i在区间[0, semi_n)迭代的过程中,
36 // max = n - 1 - i, 也逐渐向semi_n靠拢
37 for i in 0..semi_n {
38 let mut min = i;
39 let mut max = n - 1 - i;
40 if a[min] > a[max] {
41 a.swap(min, max);
42 }
43 for j in (i + 1)..(n - 1 - i) {
44 if a[min] > a[j] {
45 min = j;
46 }
47 if a[max] < a[j] {
48 max = j;
49 }
50 }
51
52 a.swap(i, min);
53 a.swap(n - 1 - i, max);
54 }
55}

Callers

nothing calls this directly

Calls 1

lenMethod · 0.45

Tested by

no test coverage detected