堆排序

  1. pub fn heap_sort<T: PartialOrd>(arr: &mut [T]) {
  2. let size = arr.len();
  3. // 构建大根堆
  4. for i in (0..size / 2).rev() {
  5. heapify(arr, i, size);
  6. }
  7. // 每轮循环将堆顶元素(也就是最大元素)放到最后
  8. for i in (1..size).rev() {
  9. arr.swap(0, i);
  10. // 恢复大根堆
  11. heapify(arr, 0, i);
  12. }
  13. }
  14. fn heapify<T: PartialOrd>(arr: &mut [T], root: usize, end: usize) {
  15. // 记录父节点和左右节点中最大元素的索引位置
  16. let mut largest = root;
  17. let left_child = 2 * root + 1;
  18. if left_child < end && arr[left_child] > arr[largest] {
  19. largest = left_child;
  20. }
  21. let right_child = left_child + 1;
  22. if right_child < end && arr[right_child] > arr[largest] {
  23. largest = right_child;
  24. }
  25. if largest != root {
  26. arr.swap(root, largest);
  27. heapify(arr, largest, end);
  28. }
  29. }
  30. #[cfg(test)]
  31. mod tests {
  32. use super::*;
  33. #[test]
  34. fn test_empty_vec() {
  35. let mut empty_vec: Vec<String> = vec![];
  36. heap_sort(&mut empty_vec);
  37. assert_eq!(empty_vec, Vec::<String>::new());
  38. }
  39. #[test]
  40. fn test_number_vec() {
  41. let mut vec = vec![7, 49, 73, 58, 30, 72, 44, 78, 23, 9];
  42. heap_sort(&mut vec);
  43. assert_eq!(vec, vec![7, 9, 23, 30, 44, 49, 58, 72, 73, 78]);
  44. }
  45. #[test]
  46. fn test_string_vec() {
  47. let mut vec = vec![
  48. String::from("Bob"),
  49. String::from("David"),
  50. String::from("Carol"),
  51. String::from("Alice"),
  52. ];
  53. heap_sort(&mut vec);
  54. assert_eq!(
  55. vec,
  56. vec![
  57. String::from("Alice"),
  58. String::from("Bob"),
  59. String::from("Carol"),
  60. String::from("David"),
  61. ]
  62. );
  63. }
  64. }