最大堆的实现

#include <iostream>
using namespace std;
class maxheap
{
private:
    int * heaparray;
    int cursize;
    int maxsize;
public:
    maxheap(int *arr,int num,int max)
    {
        heaparray=arr;
        cursize=num;
        maxsize=max;
    }
    void build()
    {
        for(int i=cursize;i<maxsize;i++)    heaparray[i]=-1;
        for(int i=cursize/2-1;i>=0;i--)     shiftdown(i);
    }
    bool isleaf(int pos)
    {
        if(cursize/2<pos)   return true;
        else    return false;
    }
    bool Remove(int pos)
    {
        int temp=heaparray[cursize-1];
        //heaparray[cursize]=heaparray[pos];
        heaparray[pos]=temp;
        shiftdown(pos);
        cursize--;
        return true;
    }
    void shiftdown(int pos)
    {
        int i=pos,j=2*i+1;
        int temp=heaparray[i];
        while(j<cursize)
        {
            if((j<cursize-1)&&(heaparray[j]<heaparray[j+1]))
                j++;
            if(temp<heaparray[j])
            {
                heaparray[i]=heaparray[j];
                i=j;
                j=j*2+1;
            }
            else    break;
        }
        heaparray[i]=temp;
    }
    void shiftup(int pos)
    {
        int i=pos,j=(i-1)/2;
        int temp=heaparray[i];
        while(j!=0||i!=0)
        {
            if(heaparray[j]>temp)               break;
            else if(heaparray[j]==temp)
            {
                cout<<"ÒÑ´æÔÚ"<<endl;
                break;
            }
            else
            {
                heaparray[i]=heaparray[j];
                i=j;
                j=(i-1)/2;
            }
        }
        heaparray[i]=temp;
    }
    maxheap Insert(maxheap m,const int node)
    {
        m.heaparray[m.cursize++]=node;
        m.build();
        return m;
    }
    bool Insert(const int node)
    {
        heaparray[cursize++]=node;
        shiftup(cursize-1);
    }
    void Show()
    {
        for(int i=0;i<cursize;i++)
        {
            cout<<heaparray[i]<<"  ";
        }
        cout<<endl;
    }
};
int main()
{
    int a[20]={20,12,35,15,10,80,30,17,2,1};
    maxheap mh(a,10,20);
    for(int i=0;i<10;i++)       cout<<a[i]<<"  ";
    cout<<endl;
    cout<<"build:"<<endl;
    mh.build();
    mh.Show();
    cout<<"insert 666:"<<endl;
    mh.Insert(666);
    mh.Show();
    cout<<"insert 36:"<<endl;
    mh.Insert(36);
    mh.Show();
    cout<<"remove pos:3"<<endl;
    mh.Remove(3);
    mh.Show();
    cout<<"remove pos:0"<<endl;
    mh.Remove(0);
    mh.Show();
    cout << "Hello world!" << endl;
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值