堆排序 是利用堆 这种数据结构而设计的一种排序算法,堆排序是一种选择排序,它的最坏,最好,平均时间复杂度均为O(nlogn),它是不稳定排序。
堆的性质:是一棵完全二叉树,并且父节点的值大于它所有子节点的值(最大堆)
堆调整(heapfiy):若子节点c1,c2有大于父节点parent的值,则与父节点交换。
堆排序的基本思想是:将待排序序列构造成一个最大堆,此时,整个序列的最大值就是堆顶的根节点。将其与末尾元素进行交换,此时末尾就为最大值。然后将剩余n-1个元素重新构造成一个堆,这样会得到n个元素的次小值。如此反复执行,便能得到一个有序序列了
public class HeapSort {
//堆排序
private static void heapSort(int[] tree, int n) {
buildHeap(tree, n);
for(int i = n-1;i >= 0;i--) {
swap(tree,0,i);//把最大的放最后面
heapify(tree, 0, i);//调整
}
}
//构建最大堆
private static void buildHeap(int[] tree, int n) {
int lastNode = tree.length-1;
int parent = (lastNode-1)/2;
//从下往上构建
for(int i = parent;i >= 0;i--) {
heapify(tree,i,n);
}
}
//在左子节点,右子节点中找出最大值与父节点替换,形成局部最大堆
private static void heapify(int[] tree, int i, int n) {
int max = i;
int c1 = 2*i+1;
int c2 = 2*i+2;
if(c1<n&&tree[c1]>tree[max]) {
max = c1;
}
if(c2<n&&tree[c2]>tree[max]) {
max = c2;
}
if(max!=i) {
swap(tree,i,max);
heapify(tree,max,n);
}
}
//交换
private static void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
public static void main(String[] args) {
int tree[] = {2,5,3,1,10,4};
heapSort(tree,tree.length);
System.out.println(Arrays.toString(tree));//[1, 2, 3, 4, 5, 10]
}
}