鸡尾酒排序

  1. pub fn cocktail_shaker_sort<T: Ord>(arr: &mut [T]) {
  2. let len = arr.len();
  3. if len == 0 {
  4. return;
  5. }
  6. loop {
  7. let mut swapped = false;
  8. for i in 0..(len - 1).clamp(0, len) {
  9. if arr[i] > arr[i + 1] {
  10. arr.swap(i, i + 1);
  11. swapped = true;
  12. }
  13. }
  14. if !swapped {
  15. break;
  16. }
  17. swapped = false;
  18. for i in (0..(len - 1).clamp(0, len)).rev() {
  19. if arr[i] > arr[i + 1] {
  20. arr.swap(i, i + 1);
  21. swapped = true;
  22. }
  23. }
  24. if !swapped {
  25. break;
  26. }
  27. }
  28. }
  29. #[cfg(test)]
  30. mod tests {
  31. use super::*;
  32. #[test]
  33. fn basic() {
  34. let mut arr = vec![5, 2, 1, 3, 4, 6];
  35. cocktail_shaker_sort(&mut arr);
  36. assert_eq!(arr, vec![1, 2, 3, 4, 5, 6]);
  37. }
  38. #[test]
  39. fn empty() {
  40. let mut arr = Vec::<i32>::new();
  41. cocktail_shaker_sort(&mut arr);
  42. assert_eq!(arr, vec![]);
  43. }
  44. #[test]
  45. fn one_element() {
  46. let mut arr = vec![1];
  47. cocktail_shaker_sort(&mut arr);
  48. assert_eq!(arr, vec![1]);
  49. }
  50. #[test]
  51. fn pre_sorted() {
  52. let mut arr = vec![1, 2, 3, 4, 5, 6];
  53. cocktail_shaker_sort(&mut arr);
  54. assert_eq!(arr, vec![1, 2, 3, 4, 5, 6]);
  55. }
  56. }