利用二叉堆排序其实就是循环移除顶部元素到数组末尾,然后利用Sink重建堆的操作。
实现代码如下:
public static void headSort(int[] data) {
int n = data.length;
for(int i = 0; i < n; i++) {
creatMaxHeap(data, n - 1 - i);
swap(data, 0 , n - 1 - i);
}
}
创建最大二叉堆:
使用自下而上的方法创建二叉堆的方法为,分别对叶子结点的上一级节点以从上至下的方式重建堆。
public static void creatMaxHeap(int[] data, int lastIndex) {
for(int i = (lastIndex - 1) / 2; i >= 0; i--) {
sink(data, i, lastIndex);
}
}
由上至下的重新建堆操作:
当某一节点比其子节点要小的时候,就违反了二叉堆的定义,需要和其子节点进行交换以重新建堆,直到该节点都大于其子节点为止:
public static void sink(int[] data, int i, int lastIndex) {
while(2 * i + 1 <= lastIndex) {
int childIndex = 2 * i + 1;
if(childIndex < lastIndex) {
if(data[childIndex] < data[childIndex + 1]) childIndex++;
}
if(data[i] > data[childIndex]) break;
swap(data, i , childIndex);
i = childIndex;
}
}
附上代码:
public class HeatSort {
public static void main(String[] args) {
int[] data = new int[] {3,2,1,4,6,5};
headSort(data);
print(data);
}
public static void headSort(int[] data) {
int n = data.length;
for(int i = 0; i < n; i++) {
creatMaxHeap(data, n - 1 - i);
swap(data, 0 , n - 1 - i);
print(data);
}
}
public static void creatMaxHeap(int[] data, int lastIndex) {
for(int i = (lastIndex - 1) / 2; i >= 0; i--) {
sink(data, i, lastIndex);
}
}
public static void sink(int[] data, int i, int lastIndex) {
while(2 * i + 1 <= lastIndex) {
int childIndex = 2 * i + 1;
if(childIndex < lastIndex) {
if(data[childIndex] < data[childIndex + 1]) childIndex++;
}
if(data[i] > data[childIndex]) break;
swap(data, i , childIndex);
i = childIndex;
}
}
public static void swap(int[] data, int i, int j) {
int temp = data[i];
data[i] = data[j];
data[j] = temp;
}
public static void print(int[] data) {
for (int i = 0; i < data.length; i++) {
System.out.print(data[i] + "\t");
}
System.out.println();
}
}