梳排序

  1. pub fn comb_sort<T: Ord>(arr: &mut [T]) {
  2. let mut gap = arr.len();
  3. let shrink = 1.3;
  4. let mut sorted = false;
  5. while !sorted {
  6. gap = (gap as f32 / shrink).floor() as usize;
  7. if gap <= 1 {
  8. gap = 1;
  9. sorted = true;
  10. }
  11. for i in 0..arr.len() - gap {
  12. let j = i + gap;
  13. if arr[i] > arr[j] {
  14. arr.swap(i, j);
  15. sorted = false;
  16. }
  17. }
  18. }
  19. }
  20. #[cfg(test)]
  21. mod tests {
  22. use super::*;
  23. #[test]
  24. fn descending() {
  25. //descending
  26. let mut ve1 = vec![6, 5, 4, 3, 2, 1];
  27. comb_sort(&mut ve1);
  28. for i in 0..ve1.len() - 1 {
  29. assert!(ve1[i] <= ve1[i + 1]);
  30. }
  31. }
  32. #[test]
  33. fn ascending() {
  34. //pre-sorted
  35. let mut ve2 = vec![1, 2, 3, 4, 5, 6];
  36. comb_sort(&mut ve2);
  37. for i in 0..ve2.len() - 1 {
  38. assert!(ve2[i] <= ve2[i + 1]);
  39. }
  40. }
  41. }