堆排序

 堆排序总的流程为:构建堆—>拿出堆顶元素—>调整剩余堆;重复第2、3步直至堆为空。

 1 import java.util.Arrays;
 2 
 3 public class MyHeapSort {
 4     /*
 5     此处为大顶堆
 6      */
 7     public static void main(String[] args) {
 8         int num[] = {10, 8, 33, 54, 1, 6, 12, 43, 32, 27};
 9         heapSort(num, num.length);
10         System.out.println(Arrays.toString(num));
11     }
12 
13     private static void heapSort(int[] num, int n) {
14         /*
15         建堆,起始位置为第一个非叶结点
16          */
17         for (int i = num.length / 2 - 1; i >= 0; i--) {
18             heapAdjust(num, i, n);
19         }
20         /*
21         排序
22         拿出堆顶元素与堆中最后一个叶子结点交换,然后再进行堆调整
23          */
24         for (int i = n - 1; i >= 0; i--) {
25             swap(num, i, 0);
26             //每次拿出堆顶元素,堆的大小都要减一
27             heapAdjust(num, 0, i);
28         }
29     }
30 
31     //堆调整
32     private static void heapAdjust(int[] num, int index, int n) {
33         //父结点和左右子结点在数组中索引的关系
34         int parent = index;
35         int left = index * 2 + 1;
36         int right = index * 2 + 2;
37         //因为是构建大顶堆,所以如果父结点元素小于孩子结点元素,则交换
38         if (left < n && num[parent] < num[left]) {
39             parent = left;
40         }
41         if (right < n && num[parent] < num[right]) {
42             parent = right;
43         }
44         if (parent != index) {
45             swap(num, parent, index);
46             heapAdjust(num, parent, n);
47         }
48 
49     }
50     //交换数组中两个元素位置
51     private static void swap(int num[], int m, int n) {
52         int temp = num[n];
53         num[n] = num[m];
54         num[m] = temp;
55     }
56 }

参考连接:(感谢UP主)

https://www.bilibili.com/video/BV1fp4y1D7cj?from=search&seid=1707288375336304667

原文地址:https://www.cnblogs.com/zz-1120-wtenlb/p/13372418.html