插入排序

  1. pub fn insertion_sort<T: PartialOrd>(arr: &mut [T]) {
  2. // 从第二个元素开始排序
  3. for i in 1..arr.len() {
  4. // 找到 arr[i] 该插入的位置
  5. let mut j = i;
  6. while j > 0 && arr[j - 1] > arr[j] {
  7. arr.swap(j - 1, j);
  8. j -= 1;
  9. }
  10. }
  11. }
  12. // 这里需要 T: Ord 是因为 binary_search() 方法的限制
  13. pub fn insertion_sort_binary_search<T: Ord>(arr: &mut[T]) {
  14. // 从第二个元素开始排序
  15. for i in 1..arr.len() {
  16. // 利用二分查找获取 arr[i] 应该插入的位置
  17. let pos = arr[..i].binary_search(&arr[i]).unwrap_or_else(|pos| pos);
  18. let mut j = i;
  19. while j > pos {
  20. arr.swap(j - 1, j);
  21. j -= 1;
  22. }
  23. }
  24. }
  25. #[cfg(test)]
  26. mod tests {
  27. use super::*;
  28. mod insertion_sort {
  29. use super::*;
  30. #[test]
  31. fn test_empty_vec() {
  32. let mut empty_vec: Vec<String> = vec![];
  33. insertion_sort(&mut empty_vec);
  34. assert_eq!(empty_vec, Vec::<String>::new());
  35. }
  36. #[test]
  37. fn test_number_vec() {
  38. let mut vec = vec![7, 49, 73, 58, 30, 72, 44, 78, 23, 9];
  39. insertion_sort(&mut vec);
  40. assert_eq!(vec, vec![7, 9, 23, 30, 44, 49, 58, 72, 73, 78]);
  41. }
  42. #[test]
  43. fn test_string_vec() {
  44. let mut vec = vec![
  45. String::from("Bob"),
  46. String::from("David"),
  47. String::from("Carol"),
  48. String::from("Alice"),
  49. ];
  50. insertion_sort(&mut vec);
  51. assert_eq!(
  52. vec,
  53. vec![
  54. String::from("Alice"),
  55. String::from("Bob"),
  56. String::from("Carol"),
  57. String::from("David"),
  58. ]
  59. );
  60. }
  61. }
  62. mod insertion_sort_binary_search {
  63. use super::*;
  64. #[test]
  65. fn test_empty_vec() {
  66. let mut empty_vec: Vec<String> = vec![];
  67. insertion_sort_binary_search(&mut empty_vec);
  68. assert_eq!(empty_vec, Vec::<String>::new());
  69. }
  70. #[test]
  71. fn test_number_vec() {
  72. let mut vec = vec![7, 49, 73, 58, 30, 72, 44, 78, 23, 9];
  73. insertion_sort_binary_search(&mut vec);
  74. assert_eq!(vec, vec![7, 9, 23, 30, 44, 49, 58, 72, 73, 78]);
  75. }
  76. #[test]
  77. fn test_string_vec() {
  78. let mut vec = vec![
  79. String::from("Bob"),
  80. String::from("David"),
  81. String::from("Carol"),
  82. String::from("Alice"),
  83. ];
  84. insertion_sort_binary_search(&mut vec);
  85. assert_eq!(
  86. vec,
  87. vec![
  88. String::from("Alice"),
  89. String::from("Bob"),
  90. String::from("Carol"),
  91. String::from("David"),
  92. ]
  93. );
  94. }
  95. }
  96. }