STL【Heap】

STL裏面的堆操作一般用到的只有4個。
他們就是
make_heap();、pop_heap();、push_heap();、sort_heap();

他們的頭函數是include<algorithm>

首先是make_heap();
他的函數原型是:
void make_heap(first_pointer,end_pointer,compare_function);
一個參數是數組或向量的頭指針,第二個向量是尾指針。第三個參數是比較函數的名字
。在缺省的時候,默認是大根堆。(下面的參數都一樣就不解釋了)
作用:把這一段的數組或向量做成一個堆的結構。範圍是(first,last)

複雜度O(n).

************************************************************************************************************************************************************************

然後是pop_heap();
它的函數原型是:
void pop_heap(first_pointer,end_pointer,compare_function);
作用:pop_heap()不是真的把最大(最小)的元素從堆中彈出來,而是放在最後面,對前面n-1個重新排序成堆。

複雜度O(log(n))

************************************************************************************************************************************************************************

接着是push_heap()
void pushheap(first_pointer,end_pointer,compare_function);
作用:push_heap()假設由[first,last-1)是一個有效的堆,然後,再把堆中的新元素加

進來,做成一個堆。

複雜度O(log(n))

************************************************************************************************************************************************************************

最後是sort_heap()
void sort_heap(first_pointer,end_pointer,compare_function);
作用是sort_heap對[first,last)中的序列進行排序。它假設這個序列是有效堆。(當然

,經過排序之後就不是一個有效堆了)

複雜度O(nlog(n))

************************************************************************************************************************************************************************

下面是例程:

#include<algorithm>

#include<cstdio>
using namespace std;
bool cmp(int a,int b)
{
    return a>b;
}

int main()

{
    int i,number[20]={29,23,20,22,17,15,26,51,19,12,35,40};
    make_heap(&number[0],&number[12]);//第一位是最大的!!!
    //結果是:51 35 40 23 29 20 26 22 19 12 17 15
    for(i=0;i<12;i++)
        printf("%d ",number[i]);
    printf("\n");

    make_heap(&number[0],&number[12],cmp);//第一位是最小的!!!
    //結果:12 17 15 19 23 20 26 51 22 29 35 40
    for(i=0;i<12;i++)
        printf("%d ",number[i]);
    printf("\n");

    //加入元素8
    number[12]=8;
    //加入後調整
    push_heap(&number[0],&number[13],cmp);
    //結果:8 17 12 19 23 15 26 51 22 35 40 20
    for(i=0;i<13;i++)
        printf("%d ",number[i]);
    printf("\n");

    //彈出元素8
    pop_heap(&number[0],&number[13],cmp);
    //結果:12 17 15 19 29 20 26 22 23 51 35 40 【8】
    for(i=0;i<13;i++)
        printf("%d ",number[i]);
    printf("\n");

    sort_heap(&number[0],&number[12],cmp);
    //結果不用說都知道是有序的了!
    for(i=0;i<12;i++)
        printf("%d ",number[i]);
    return 0;
}


 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

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