堆是具有下列性质的完全二叉树:每个结点的值都大于或等于其左右孩子的值,称为大顶堆;或者每个结点的值都小于或等于其左右孩子结点的值,称为小顶堆。
堆排序的平均时间复杂度为O(nlogn),空间复杂度为O(1)
public void heapSort(int[] datas) { int length = datas.length; for(int i = length / 2; i >= 0; i--) { buildHeap(datas, i, length - 1); } for(int i = length - 1; i > 0; i--) { int temp = datas[0]; datas[0] = datas[i]; datas[i] = temp; buildHeap(datas, 0, i - 1); } } private void buildHeap(int[] datas, int start, int length) { int s = start; int lc = 2 * s +1; int father = datas[s]; for(; lc <= length; s = lc, lc = 2 * lc +1) { if(lc < length && datas[lc] < datas[lc + 1]) { lc++; } if(datas[s] < datas[lc]) { father = datas[s]; datas[s] = datas[lc]; datas[lc] = father; } else { break; } } }