冒泡排序

  1. pub fn bubble_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 swapped = false;
  9. // 最后i个元素已经排好了顺序
  10. for j in 1..(size - i) {
  11. if arr[j - 1] > arr[j] {
  12. arr.swap(j - 1, j);
  13. swapped = true;
  14. }
  15. }
  16. // 如果当前循环没有发生元素交换,说明数组已经有序
  17. if !swapped {
  18. break;
  19. }
  20. }
  21. }
  22. #[cfg(test)]
  23. mod tests {
  24. use super::*;
  25. #[test]
  26. fn test_empty_vec() {
  27. let mut empty_vec: Vec<String> = vec![];
  28. bubble_sort(&mut empty_vec);
  29. assert_eq!(empty_vec, Vec::<String>::new());
  30. }
  31. #[test]
  32. fn test_number_vec() {
  33. let mut vec = vec![7, 49, 73, 58, 30, 72, 44, 78, 23, 9];
  34. bubble_sort(&mut vec);
  35. assert_eq!(vec, vec![7, 9, 23, 30, 44, 49, 58, 72, 73, 78]);
  36. }
  37. #[test]
  38. fn test_string_vec() {
  39. let mut vec = vec![
  40. String::from("Bob"),
  41. String::from("David"),
  42. String::from("Carol"),
  43. String::from("Alice"),
  44. ];
  45. bubble_sort(&mut vec);
  46. assert_eq!(
  47. vec,
  48. vec![
  49. String::from("Alice"),
  50. String::from("Bob"),
  51. String::from("Carol"),
  52. String::from("David"),
  53. ]
  54. );
  55. }
  56. }