选择排序

  1. pub fn selection_sort<T: PartialOrd>(arr: &mut [T]) {
  2. if arr.len() <= 1 {
  3. return;
  4. }
  5. let size = arr.len();
  6. for i in 0..(size - 1) {
  7. // 找到最小元素的索引值
  8. let mut min_index = i;
  9. for j in (i + 1)..size {
  10. if arr[j] < arr[min_index] {
  11. min_index = j;
  12. }
  13. }
  14. if min_index != i {
  15. arr.swap(i, min_index);
  16. }
  17. }
  18. }
  19. #[cfg(test)]
  20. mod tests {
  21. use super::*;
  22. #[test]
  23. fn test_empty_vec() {
  24. let mut empty_vec: Vec<String> = vec![];
  25. selection_sort(&mut empty_vec);
  26. assert_eq!(empty_vec, Vec::<String>::new());
  27. }
  28. #[test]
  29. fn test_number_vec() {
  30. let mut vec = vec![7, 49, 73, 58, 30, 72, 44, 78, 23, 9];
  31. selection_sort(&mut vec);
  32. assert_eq!(vec, vec![7, 9, 23, 30, 44, 49, 58, 72, 73, 78]);
  33. }
  34. #[test]
  35. fn test_string_vec() {
  36. let mut vec = vec![
  37. String::from("Bob"),
  38. String::from("David"),
  39. String::from("Carol"),
  40. String::from("Alice"),
  41. ];
  42. selection_sort(&mut vec);
  43. assert_eq!(
  44. vec,
  45. vec![
  46. String::from("Alice"),
  47. String::from("Bob"),
  48. String::from("Carol"),
  49. String::from("David"),
  50. ]
  51. );
  52. }
  53. }