package study.datastructure.sort;
import java.util.Random;
/**
* @description: 堆排序
* 时间复杂度O(n*log2n)
* 空间复杂度O(1)
* 不稳定 例子: 3(0) 大根堆排序后 3(1), 3(0), 4
* 3(1) 4
**/
public class HeapSort {
private void heapSort(int[] array, int length) {
//从 length/2 -1 的下标处开始建立堆,因为这个节点是最后一个有孩子的节点,它之前的节点都有孩子,之后的节点都没有孩子
for(int i = length/2 -1; i >= 0; i--) {
heapAdjust(array, i, length);
}
//交换堆顶节点与最后一个节点的位置,以数组长度减小1的数组重新建立堆,数组后面的数据,已经排好顺序
for(int i = length-1; i >= 0; i--) {
int temp = array[0];
array[0] = array[i];
array[i] = temp;
heapAdjust(array, 0, i-1);
}
}
/** 循环实现大根堆的建立 */
private void heapAdjust(int[] array, int parent, int length) {
int tempParent = array[parent];
int Lchild = parent*2 +1;
//最大孩子的下标默认是左孩子
int maxChild = Lchild;
while(Lchild < length) {
int Rchild = parent*2 +1 +1;
if(Rchild < length) {
maxChild = array[Lchild] > array[Rchild]? Lchild : Rchild;
}
//父节点大于所有孩子节点,直接退出循环
if(tempParent > array[maxChild]) {
break;
}
//大根堆调整
array[parent] = array[maxChild];
array[maxChild] = tempParent ;
//以最大的孩子为父节点,继续循环
parent = maxChild;
Lchild = parent*2 +1;
maxChild = Lchild;
}
}
public static void main(String arg[]) {
int length = 10;
int[] array = new int[length];
for(int i = 0; i < length; i++) {
Random data = new Random();
array[i] = data.nextInt(100);
}
new HeapSort().heapSort(array, length);
for(int date : array) {
System.out.println(date);
}
}
}