臭皮匠排序

  1. fn _stooge_sort<T: Ord>(arr: &mut [T], start: usize, end: usize) {
  2. if arr[start] > arr[end] {
  3. arr.swap(start, end);
  4. }
  5. if start + 1 >= end {
  6. return;
  7. }
  8. let k = (end - start + 1) / 3;
  9. _stooge_sort(arr, start, end - k);
  10. _stooge_sort(arr, start + k, end);
  11. _stooge_sort(arr, start, end - k);
  12. }
  13. pub fn stooge_sort<T: Ord>(arr: &mut [T]) {
  14. let len = arr.len();
  15. if len == 0 {
  16. return;
  17. }
  18. _stooge_sort(arr, 0, len - 1);
  19. }
  20. #[cfg(test)]
  21. mod test {
  22. use super::*;
  23. #[test]
  24. fn basic() {
  25. let mut vec = vec![3, 5, 6, 3, 1, 4];
  26. stooge_sort(&mut vec);
  27. for i in 0..vec.len() - 1 {
  28. assert!(vec[i] <= vec[i + 1]);
  29. }
  30. }
  31. #[test]
  32. fn empty() {
  33. let mut vec: Vec<i32> = vec![];
  34. stooge_sort(&mut vec);
  35. assert_eq!(vec, vec![]);
  36. }
  37. #[test]
  38. fn reverse() {
  39. let mut vec = vec![6, 5, 4, 3, 2, 1];
  40. stooge_sort(&mut vec);
  41. for i in 0..vec.len() - 1 {
  42. assert!(vec[i] <= vec[i + 1]);
  43. }
  44. }
  45. #[test]
  46. fn already_sorted() {
  47. let mut vec = vec![1, 2, 3, 4, 5, 6];
  48. stooge_sort(&mut vec);
  49. for i in 0..vec.len() - 1 {
  50. assert!(vec[i] <= vec[i + 1]);
  51. }
  52. }
  53. }