pub fn cocktail_shaker_sort<T: Ord + std::fmt::Debug>(arr: &mut [T]) {
let len = arr.len();
if len < 2 {
return ;
}
let mut left = 1;
let mut right = len - 1;
while left < right {
let mut sorted = true;
for index in left..right {
if arr[index - 1] > arr[index] {
arr.swap(index - 1, index);
sorted = false;
}
}
if sorted {
break;
}
right -= 1;
sorted = true;
for index in (left..right).rev() {
if arr[index - 1] > arr[index] {
arr.swap(index - 1, index);
sorted = false;
}
}
if sorted {
break;
}
left += 1;
}
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結