Node:最小堆

#include <iostream>
#include <stdlib.h>
#include <ctime>

using namespace std;

const int maxn=1010;
int heap[maxn];
int sz;

//堆從下標1開始
void deleteNode()         //最小堆
{
    //,第一個節點刪除,最後一個放到第一個位置,之後向下調整
    heap[1] = heap[sz--];
    int cur = 1, son = 2;
    //  存在兒子比父親小
    while(son <= sz && (heap[son] < heap[cur] || heap[son+1] < heap[cur]))
    {
        if(heap[son] > heap[son+1])
            son++;
        swap(heap[son],heap[cur]);

        //指針下移
        cur = son;
        son*= 2;
    }
}

void insertNode(int t)
{
    //添加到最後一個節點,向上調整
    heap[++sz] = t;
    int cur = sz, p = cur/2;
    while(p>=1)
    {
        //比父親小的節點
        if(heap[cur] < heap[p])
            swap(heap[cur],heap[p]);
        cur = p;
        p = cur/2;
    }
}

int main()
{
    int n,t;
    srand(time(0));
    while(cin>>n)
    {
        sz=0;
        for(int i=1;i<=n;i++)
        {
            t=rand()%1000;
            insertNode(t);
            //cout<<heap[1]<<endl;
        }
        for(int i=1;i<=n;i++)
        {
            if(!n%10)
                cout<<endl;
            cout<<heap[1]<<" ";
            deleteNode();
        }
        cout<<endl;
    }

    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章