堆排序可以保证最坏情况下的效率边界为O(nlogn)。如果直接用c++的priority_queue作为辅助结构来实现堆排序,会消耗额外O(n)的存储空间。我们可以直接在原数组上进行堆排序从而节省O(n)的空间开销。
代码如下,利用了c的rand函数来实现随机输入。
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
const int MAXN=15;
void siftUp(int a[],int pos)
{
int p=pos/2;
while((pos>1)&&(a[p]<a[pos]))
{
int tmp=a[p];
a[p]=a[pos];
a[pos]=tmp;
pos=p;
p=pos/2;
}
}
void siftDown(int a[],int n)
{
int pos=1;
int child=pos*2;
if(child>n)
{
return;
}
if(((child+1)<=n)&&(a[child+1]>a[child]))
{
child++;
}
while((child<=n)&&(a[pos]<a[child]))
{
int tmp=a[pos];
a[pos]=a[child];
a[child]=tmp;
pos=child;
child=pos*2;
if(((child+1)<=n)&&(a[child+1]>a[child]))
{
child++;
}
}
}
void heapSort(int a[],int n)
{
for(int i=2;i<=MAXN;++i)
{
siftUp(a,i);
}
for(int i=MAXN;i>1;--i)
{
int tmp=a[1];
a[1]=a[i];
a[i]=tmp;
siftDown(a,i-1);
}
}
int main()
{
srand(time(NULL));
int a[MAXN+1];
for(int i=1;i<=MAXN;++i)
{
a[i]=rand()%20+1;
}
heapSort(a,MAXN);
for(int i=1;i<=MAXN;++i)
{
cout<<a[i]<<" ";
}
cout<<endl;
}