堆排序原理
优先队列可以用于以时间的排序.基于该思想的算法叫做堆排序.堆排序是指,将N个元素按照(max)堆的方式存入数组中,这个过程的时间复杂度为
,然后再经过
次deleteMax,每次deleteMax都会将堆的top与堆末位置相交换,这样一来大大节约了算法的空间开销,由于每次deleteMax花费时间
,因此总的运行时间为
.
堆排序策略
1.将原始数组构建为Max堆
2.循环N-1次删除Max堆的最大值,同时将最大值与堆末位置交换
例如,原始数组为:
31 | 41 | 59 | 26 | 53 | 58 | 97 |
构造成Max堆为:
97 | 53 | 59 | 26 | 41 | 58 | 31 |
(PS:构造原理同优先队列,顶部为最大值,对数组中的每一个节点i,都有左儿子的位置为2i,右儿子的位置为2i+1,父节点的位置为i/2,并且父节点大于子节点)
第一次deleteMax后:
59 | 53 | 58 | 26 | 41 | 31 | 97 |
经过N-1次deleteMax后:
26 | 31 | 41 | 53 | 58 | 59 | 97 |
堆排序代码实现
/*****
* 堆排序与优先队列相似,不同的是优先队列为min堆,而堆排序是将max堆进行N-1次deleteMax.
* 将顶部删除后的元素重新放到数组中,在最后一个元素被删除后,整个数组就是一个升序数组
* 堆排序的最好时间复杂度为O(N log N);
* buildeHeap为O(N)
* 每次deleteMax为O(logN)
*/
public static void heapSort(int[] a){
for(int i = a.length/2-1;i>=0;i--) // bulidHeap
percDown(a,i,a.length);
for(int i = a.length - 1; i > 0; i--){
swapReference(a,0,i); //deleteMin
percDown(a,0,i);
}
}
public static void percDown(int[] a, int i, int n){//下滤
int child;
int temp;
for(temp = a[i];leftChild(i) < n; i = child){
child = leftChild(i);
if(child != n-1 && a[child] < a[child +1])
child++;
if(temp < a[child])
a[i] = a[child];
else
break;
}
a[i] = temp;
}
public static void swapReference(int[] a, int top,int bottom){
int tmp = a[top];
a[top] = a[bottom];
a[bottom] = tmp;
}
public static int leftChild(int i){
return 2*i + 1;
}
定理
对N个互异项的随机排列进行堆排序所用比较的平均次数为.