用最小堆实现优先队列

最近在复习数据结构,文章所使用c++,因时间仓促,使用的是较简单的C风格,稍作改动即可面向对象操作。代码粗糙:

#include <iostream>
#include <algorithm>
using namespace std;

int *heap;
int n;
void heapadjast(int start,int length)
{
    int cur=start;
    int child=start*2+1;
    int temp=heap[cur];
    while(child<=length)
    {
        if(child+1<=length&&heap[child+1]<heap[child])child++;
        if(temp<heap[child])
            break;
        else
        {
            heap[cur]=heap[child];
            cur=child;
            child=2*child+1;
        }
    }
    heap[cur]=temp;
}
void swep(int *a,int i,int j)
{
    int temp=a[j];
    a[j]=a[i];
    a[i]=temp;
}
void heapsort()
{
    for(int i=(n-2)/2;i>=0;i--)
    {
        heapadjast(i,n-1);
    }
    /*for(int i=n-1;i>0;--i)
    {
        swep(heap,0,i);
        heapadjast(0,i-1);
    }*/
}

void siftUP(int pos)
{
    int cur=pos;
    int par=(pos-1)/2;
    int temp=heap[cur];
    while(cur)
    {
        if(temp>=heap[par])
            break;
        else
        {
            heap[cur]=heap[par];
            cur=par;
            par=(par-1)/2;
        }
    }
    heap[cur]=temp;
}
void insertq(int num,int *heap)
{
    heap[n]=num;
    n++;
    siftUP(n-1);
}
void removeq()
{
    heap[0]=heap[n-1];
    n--;
    heapadjast(0,n-1);
}
int main()
{
    int Maxsize=20;
    int arr[]={0,9,5,1,4,7,11,13,12,111};
    n=0;
    heap=new int[Maxsize];
    for(int i=0;i<10;i++)
    {
        insertq(arr[i],heap);
    }
    heapsort();
    insertq(6,heap);
    for(int i=0;i<n;i++)
        cout<<heap[i]<<" ";
        cout<<endl;
        while(n)
        {
            cout<<heap[0]<<" ";
            removeq();
        }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值