注:我测试所用数据都是可以比较大小的类型且无重复元素,且排序按照升序排列。
1、堆排序算法分析
我们可以通过建立一个二叉堆来对元素进行排序,有两种思路,一是先将这些元素建立一个二叉堆,执行N次删除最大元素的操作,用一个数组接收被删除的数据,这样就得到了元素的升序排列。这个算法的主要问题就是使用了一个附加数组,增大了空间开销,第二种实现方法是因为每次删除最大元素后堆的长度减1,所以可以将被删除的元素放在堆中的最后单元,当删除结束后就得到了升序排列。
2、堆排序代码
以数组形式储存的堆有一定的顺序,且简化了操作在大部分计算上的运行速度很可能非常快,结点下标为 i 的结点,其父结点下标为 i/2,其左儿子为 2i-1,右儿子为2i。
typedef int ElementType;
#define LeftChild(i) (2*(i)+1)
void PercDown(ElementType a[],int i,int n){
int Child;
ElementType temp;
for(temp=a[i];LeftChild(i)<n;i=Child){
Child=LeftChild(i);
if(Child!=n-1&&a[Child+1]>a[Child]) Child++;
if(temp<a[Child]) a[i]=a[Child];
else break;
}
a[i]=temp;
}
void Heapsort(ElementType a[],int n){
int i;
for(i=n/2;i>=0;i--) PercDown(a,i,n); //Build Heap
for(i=n-1;i>0;i--){
Swap(&a[0],&a[i]); //Delete the max
PercDown(a,0,i);
}
}
3、堆排序分析
1、时间复杂度
优先队列可以用于花费O(N log N)时间的排序,建立N个元素的二叉堆花费O(N)时间,然后执行N次删除最大元素操作每次花费O( logN)的时间,所以总的运行时间是O(N logN)。
2、运行时间实例分析
在这里我生成一个从1——N的随机数数组,N的选取为10000,1000000,1000000,太小了运行时间太短,注意要在main函数外面声明数组,main函数中声明的数组长度不能太大,因为main函数里面是局部变量放在堆栈段,局部变量太大会导致栈溢出。我在我的电脑上运行10次取平均值 。
生成随机数组的函数:
void Randomize(ElementType num[],int length){
int i=0;
srand((ElementType)time(NULL));
for(;i<length;i++) num[i]=i+1;
for(i=length-1;i>0;i--) Swap(&num[i],&num[rand()%i]);
}
void Swap(ElementType* a,ElementType* b){
ElementType temp=*a;
*a=*b;
*b=temp;
}
不同数组长度下的平均运行时间:
10000 | 100000 | 1000000 | 10000000 |
---|---|---|---|
0 | 0.0157 | 0.18 | 1.981 |
4、整体代码
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
typedef int ElementType;
#define LeftChild(i) (2*(i)+1)
void PercDown(ElementType [],int,int);
void Heapsort(ElementType [],int);
void Swap(ElementType*,ElementType*);
void Randomize(ElementType [],int); //随机化一个数组,参数为数组地址和长度
const int N=10000;
ElementType num[N];
int main(void){
clock_t start=0,finish=0;
Randomize(num,N);
start=clock();
Heapsort(num,N);
finish=clock();
//for(int i=0;i<N;i++) printf("%d\n",num[i]);
printf("\n本次排序用时:\n%lf",(double)(finish-start)/CLOCKS_PER_SEC);
return 0;
}
void PercDown(ElementType a[],int i,int n){
int Child;
ElementType temp;
for(temp=a[i];LeftChild(i)<n;i=Child){
Child=LeftChild(i);
if(Child!=n-1&&a[Child+1]>a[Child]) Child++;
if(temp<a[Child]) a[i]=a[Child];
else break;
}
a[i]=temp;
}
void Heapsort(ElementType a[],int n){
int i;
for(i=n/2;i>=0;i--) PercDown(a,i,n); //Build Heap
for(i=n-1;i>0;i--){
Swap(&a[0],&a[i]); //Delete the max
PercDown(a,0,i);
}
}
void Swap(ElementType* x,ElementType* y){
ElementType temp=*x;
*x=*y;
*y=temp;
}
void Randomize(ElementType a[],int length){
memset(a,0,sizeof(a));
srand((ElementType)time(NULL));
for(int i=0;i<length;i++) a[i]=i+1;
for(int i=length-1;i>0;i--) Swap(&a[i],&a[rand()%i]);
}
总结
总的来看,堆排序是一种比较好的算法,它是基于优先队列的基础上一种比较稳定的排序算法。