1.什么是堆
堆是完全二叉树。堆分为最大堆和最小堆。最大堆是根节点大于等于左右子树;最小堆是根节点小于等于左右子树。存储堆最常用的数据结构是数组:所以最大堆的表示:array[i] >= array[2 * i] && array[i] >= array[2 * i + 2];最小堆的表示:array[i] <= array[2 * i] && array[i] <= array[2 * i + 2]。因为用数组存储且堆是是完全二叉树,所以其根节点的索引范围是0-array.length / 2
2.堆排序的步骤
1)初始化堆,即建立无须的最大堆或最小堆
2)将堆顶元素和最后一个元素交换,重新调整0至n-1节点,使其成为堆
3)重复步骤2)
3.堆排序的实现
第一步建堆,第二步交换堆顶和最后一个元素,第三步调整其余元素使其成为堆
<pre name="code" class="html">public static void heapSort(int[] array) {
// build the initial heap
buildHeap(array);
// swap the first and the last node
for (int i = array.length - 1; i >= 0; i--) {
swap(array, 0, i);
adjustHeap(array, 0, i);
}
}
初始化堆的时候,也是通过不断的调整,使其成为堆
private static void buildHeap(int[] array) {
for (int i = array.length / 2; i >= 0 ; i--) {
adjustHeap(array, i, array.length);
}
}
private static void adjustHeap(int[] array, int rootIndex, int length) {
int leftIndex = 2 * rootIndex + 1;
int rightIndex = 2 * rootIndex + 2;
int maxIndex = rootIndex;
// if the node is left, no adjust
if (maxIndex <= length / 2) {
// find the max number index in rootIndex, leftIndex, rightIndex
if (leftIndex < length && array[leftIndex] > array[maxIndex]) {
maxIndex = leftIndex;
}
if (rightIndex < length && array[rightIndex] > array[maxIndex]) {
maxIndex = rightIndex;
}
// make the root is max
if (maxIndex != rootIndex) {
swap(array, rootIndex, maxIndex);
// make sure the heap after swap
adjustHeap(array, maxIndex, length);
}
}
}
调整堆的代码思路比较明确:比较堆顶和左右子树的大小,将最大的放在堆顶,若交换之后的叶子节点也有子树,则继续比较。
以上代码使用的是递归。
下面使用的非递归的方式
private static void adjustHeapNon(int[] array, int rootIndex, int length) {
int maxIndex = rootIndex;
// if the node is left, no adjust
while (maxIndex <= length / 2) {
int leftIndex = 2 * rootIndex + 1;
int rightIndex = 2 * rootIndex + 2;
// find the max number index in rootIndex, leftIndex, rightIndex
if (leftIndex < length && array[leftIndex] > array[maxIndex]) {
maxIndex = leftIndex;
}
if (rightIndex < length && array[rightIndex] > array[maxIndex]) {
maxIndex = rightIndex;
}
// make the root is max
if (maxIndex != rootIndex) {
swap(array, rootIndex, maxIndex);
rootIndex = maxIndex;
} else {
break;
}
}
}
参考资料:
http://www.cnblogs.com/dolphin0520/archive/2011/10/06/2199741.html