地精排序

  1. use std::cmp;
  2. pub fn gnome_sort<T>(arr: &[T]) -> Vec<T>
  3. where
  4. T: cmp::PartialEq + cmp::PartialOrd + Clone,
  5. {
  6. let mut arr = arr.to_vec();
  7. let mut i: usize = 1;
  8. let mut j: usize = 2;
  9. while i < arr.len() {
  10. if arr[i - 1] < arr[i] {
  11. i = j;
  12. j = i + 1;
  13. } else {
  14. arr.swap(i - 1, i);
  15. i -= 1;
  16. if i == 0 {
  17. i = j;
  18. j += 1;
  19. }
  20. }
  21. }
  22. arr
  23. }
  24. #[cfg(test)]
  25. mod tests {
  26. use super::*;
  27. #[test]
  28. fn basic() {
  29. let res = gnome_sort(&vec![6, 5, -8, 3, 2, 3]);
  30. assert_eq!(res, vec![-8, 2, 3, 3, 5, 6]);
  31. }
  32. #[test]
  33. fn already_sorted() {
  34. let res = gnome_sort(&vec!["a", "b", "c"]);
  35. assert_eq!(res, vec!["a", "b", "c"]);
  36. }
  37. #[test]
  38. fn odd_number_of_elements() {
  39. let res = gnome_sort(&vec!["d", "a", "c", "e", "b"]);
  40. assert_eq!(res, vec!["a", "b", "c", "d", "e"]);
  41. }
  42. #[test]
  43. fn one_element() {
  44. let res = gnome_sort(&vec![3]);
  45. assert_eq!(res, vec![3]);
  46. }
  47. #[test]
  48. fn empty() {
  49. let res = gnome_sort(&Vec::<u8>::new());
  50. assert_eq!(res, vec![]);
  51. }
  52. }