奇偶排序

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