1、堆排序的时间复杂度与归并排序相同,O(nlogn)。堆排序的优势在与他只需要固定数量的额外空间,堆排序要比空间复杂性为O(n)的归并排序稍微慢一些,但是比空间复杂性为O(1)的归并排序要快。
2、对序列(26, 5, 77, 1, 61, 11, 59, 15, 48, 19)进行堆排序
过程:
代码:
#include<iostream>
using namespace std;
#define max_size 11
void adjust(int list[], int root, int n);
void heapSort(int list[]);
/*
* 调整最大堆(二叉堆)
*/
void adjust(int list[], int root, int n) {
int rootkey, child , temp;
rootkey = temp = list[root];
child = 2*root;
while(child <= n) {
if((child<n) && list[child]<list[child+1]) {
child++;
}
if(rootkey > list[child]) {
break;
} else {
list[child/2] = list[child];
child *= 2;
}
}
//向上调整,所以最后要处理root 中的值
list[child/2] = temp;
}
void heapSort(int list[]) {
int i, j;
int n = max_size-1;
//创建最大堆
for(i = n/2; i>0; i--) {
adjust(list, i, n);
}
//将root删除(放在数组的最后),调整最大堆
for(j = n-1; j>0; j--) {
list[1] = list[1] + list[j+1]- (list[j+1] = list[1]);
adjust(list, 1, j);
}
}
int main() {
int list[max_size];
list[1] = 26;
list[2] = 5;
list[3] = 77;
list[4] = 1;
list[5] = 61;
list[6] = 11;
list[7] = 59;
list[8] = 15;
list[9] = 48;
list[10] = 19;
for(int i = 1; i<max_size; i++) {
cout<<list[i]<<" ";
}
cout<<endl;
heapSort(list);
for(int i = 1; i<max_size; i++) {
cout<<list[i]<<" ";
}
cout<<endl;
return 0;
}