MCPcopy Create free account
hub / github.com/QMHTMY/RustBook / cocktail_sort

Function cocktail_sort

code/chapter06/cocktail_sort.rs:3–32  ·  view source on GitHub ↗
(nums: &mut [i32])

Source from the content-addressed store, hash-verified

1// cocktail_sort.rs
2
3fn cocktail_sort(nums: &mut [i32]) {
4 if nums.len() <= 1 { return; }
5
6 // bubble 控制是否继续冒泡
7 let mut bubble = true;
8 let len = nums.len();
9 for i in 0..(len >> 1) {
10 if bubble {
11 bubble = false;
12
13 // 从左到右冒泡
14 for j in i..(len - i - 1) {
15 if nums[j] > nums[j+1] {
16 nums.swap(j, j+1);
17 bubble = true
18 }
19 }
20
21 // 从右到左冒泡
22 for j in (i+1..=(len - i - 1)).rev() {
23 if nums[j] < nums[j-1] {
24 nums.swap(j, j-1);
25 bubble = true
26 }
27 }
28 } else {
29 break;
30 }
31 }
32}
33
34fn main() {
35 let mut nums = [1,3,2,8,3,6,4,9,5,10,6,7];

Callers 1

mainFunction · 0.70

Calls 1

lenMethod · 0.45

Tested by

no test coverage detected