1 import java.util.Arrays;
2
3 /*
4 * 思路:
5 * 1.方法adjustDown:对于一个数组a[],针对第i个数进行向下(直到len-1)调整,使得该位置成为大顶堆
6 * 2.方法bulidMaxHeap:从len/2-1位置到0位置,循环调用adjustDown,使其成为大顶堆
7 * 3.方法heapSort:建立大顶堆,让第一个与最后一个调换位置,然后将第一个adjustDown一下。循环。
8 */
9 public class HeapSort {
10 //建立大顶堆
11 public static void buildMaxHeap(int[] a) {
12 for(int i=(a.length/2)-1;i>=0;i--) {
13 adjustDown(a,i,a.length);
14 }
15 }
16 //向下调整
17 public static void adjustDown(int[] a,int i,int len) {
18 int temp,j;
19 temp=a[i];
20 for(j=2*i+1;j<len;j=2*j+1) { //j为当前i的子节点,默认为左节点
21 if(j+1<len&&a[j+1]>a[j]) //如果右节点大,则选右节点
22 j++;
23 if(a[j]<=temp) //若子节点都比初始值temp小,说明找到了位置
24 break;
25 else {
26 a[i]=a[j]; //如果没有终止,那么将子节点中数值大的上调至i处
27 i=j; //同时i下降到j这个位置
28 }
29 }
30 a[i]=temp; //将temp放在最终的位置
31 }
32 //堆排序
33 public static void heapSort(int[] a) {
34 buildMaxHeap(a);
35 for(int i=a.length-1;i>=0;i--) {
36 int temp=a[0];
37 a[0]=a[i];
38 a[i]=temp;
39 adjustDown(a,0,i); //将剩余len-1调整为大顶堆,循环,所以用i表示
40 }
41 }
42 public static void main(String[] args) {
43 int[] a= {5,88,45,37,91,26,13,66,50};
44 heapSort(a);
45 System.out.println(Arrays.toString(a));
46 }
47 }