插入法建立一個最大堆

//用插入的方法建堆
#include <iostream>
#define PARENT(i) i>>1
using namespace std;

void MAX_HEAP_INSERT(int A[],int next)
{
    while(1)
    {
        int par=PARENT(next);
        if(next>1 && A[par]<A[next])
        {
            int temp=A[par];
            A[par]=A[next];
            A[next]=temp;
            next=par;
        }
        else break;
    }
}

void BUILD_MAX_HEAP(int A[],int heap_size)
{
    if(heap_size<2)
    {
        if(heap_size==1) return;
        else cout<<"heapsize wrong"<<endl;
    }
    for(int i=2;i<heap_size+1;i++)
    {
        MAX_HEAP_INSERT(A,i);
    }
}

int main(int argc, char *argv[])
{
    int n;
    cin>>n;
    int test[n+1];
    for(int i=1;i<n+1;i++) cin>>test[i];

    BUILD_MAX_HEAP(test,n);

    for(int i=1;i<n+1;i++) cout<<test[i]<<" ";
    cout<<endl;
    cout << "Hello World!" << endl;
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章