一、思想
- 堆的初始化,由最底层逐渐向上一层方向,把最大值向上移动,且$heap(parent) >= max(heap(leftchild), heap(rightchild))$
- 将最大值移到数组的尾部,将数组尾部的值移动到堆顶。左右孩子的结点各自比较,向上把最大结点的值移动上去。
- 父节点为n,$leftchild=2^{n}$, $rightchild=2^{n}+1$。(起始为根节点下标为1)
二、一些计算
1、 满二叉树结点个数$n=2^{i}-1$(等比数列求和$n=frac{a_{0}(1-q^{i})}{1-q}$,复习)。
2、因此最后一个结点的位置设为n,$frac{n}{2}$就是最后一个父节点的位置了。
三、Code
1 package algorithm; 2 3 /** 4 * Created by adrian.wu on 2019/2/19. 5 */ 6 public class HeapSort { 7 /* 8 1、Parent * 2 + 1 is left child 9 2、Parent * 2 + 2 is right child 10 */ 11 12 public void headAdjust(int[] array, int parent, int length) { 13 int pv = array[parent]; 14 15 int left = 2 * parent + 1, right = left + 1; 16 17 while (left < length) { 18 if (right < length && array[left] < array[right]) left = right; 19 if (pv >= array[left]) break; 20 array[parent] = array[left]; 21 parent = left; 22 left = 2 * left + 1; 23 right = left + 1; 24 } 25 26 array[parent] = pv; 27 } 28 29 /* 30 1、sort from back to front 31 2、 32 */ 33 public void heapSort(int[] array) { 34 //create heap, i-1(when root index starting from 0, if 1 that i is 1) 35 for (int i = array.length / 2; i >= 0; i--) { 36 headAdjust(array, i-1, array.length); 37 } 38 39 //move the head to the end of the list, then recreate the head. 40 for (int i = array.length - 1; i > 0; i--) { 41 int temp = array[i]; 42 array[i] = array[0]; 43 array[0] = temp; 44 headAdjust(array, 0, i); 45 } 46 } 47 }