堆排序实现

堆排序可以保证最坏情况下的效率边界为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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值