归并排序

  1. pub fn merge_sort<T>(arr: &mut [T])
  2. where
  3. T: PartialOrd + Clone + Default,
  4. {
  5. if arr.len() > 1 {
  6. merge_sort_range(arr, 0, arr.len() - 1);
  7. }
  8. }
  9. fn merge_sort_range<T>(arr: &mut [T], lo: usize, hi: usize)
  10. where
  11. T: PartialOrd + Clone + Default,
  12. {
  13. // 只有当元素个数大于一时才进行排序
  14. if lo < hi {
  15. let mid = lo + ((hi - lo) >> 1);
  16. merge_sort_range(arr, lo, mid);
  17. merge_sort_range(arr, mid + 1, hi);
  18. merge_two_arrays(arr, lo, mid, hi);
  19. }
  20. }
  21. // 合并两个有序数组: arr[lo..=mid], arr[mid + 1..=hi]
  22. fn merge_two_arrays<T>(arr: &mut [T], lo: usize, mid: usize, hi: usize)
  23. where
  24. T: PartialOrd + Clone + Default,
  25. {
  26. // 这里需要 clone 数组元素
  27. let mut arr1 = arr[lo..=mid].to_vec();
  28. let mut arr2 = arr[mid + 1..=hi].to_vec();
  29. let (mut i, mut j) = (0, 0);
  30. while i < arr1.len() && j < arr2.len() {
  31. if arr1[i] < arr2[j] {
  32. arr[i + j + lo] = std::mem::take(&mut arr1[i]);
  33. i += 1;
  34. } else {
  35. arr[i + j + lo] = std::mem::take(&mut arr2[j]);
  36. j += 1;
  37. }
  38. }
  39. while i < arr1.len() {
  40. arr[i + j + lo] = std::mem::take(&mut arr1[i]);
  41. i += 1;
  42. }
  43. while j < arr2.len() {
  44. arr[i + j + lo] = std::mem::take(&mut arr2[j]);
  45. j += 1;
  46. }
  47. }
  48. #[cfg(test)]
  49. mod tests {
  50. use super::*;
  51. #[test]
  52. fn test_empty_vec() {
  53. let mut empty_vec: Vec<String> = vec![];
  54. merge_sort(&mut empty_vec);
  55. assert_eq!(empty_vec, Vec::<String>::new());
  56. }
  57. #[test]
  58. fn test_number_vec() {
  59. let mut vec = vec![7, 49, 73, 58, 30, 72, 44, 78, 23, 9];
  60. merge_sort(&mut vec);
  61. assert_eq!(vec, vec![7, 9, 23, 30, 44, 49, 58, 72, 73, 78]);
  62. }
  63. #[test]
  64. fn test_string_vec() {
  65. let mut vec = vec![
  66. String::from("Bob"),
  67. String::from("David"),
  68. String::from("Carol"),
  69. String::from("Alice"),
  70. ];
  71. merge_sort(&mut vec);
  72. assert_eq!(
  73. vec,
  74. vec![
  75. String::from("Alice"),
  76. String::from("Bob"),
  77. String::from("Carol"),
  78. String::from("David"),
  79. ]
  80. );
  81. }
  82. }