C 堆的實現

2021-08-20 08:45:36 字數 1605 閱讀 6216

堆是乙個完全二叉樹。

堆根據元素的排列方式,可以分為最大堆(max-heap)和最小堆(min-heap),其中:

堆並不歸屬於stl庫容器元件,而是作為優先佇列(priority queue)的底層實現。堆是一種完全二叉樹,整棵二叉樹除了最底層的葉子節點之外是填滿的,而最底層的葉子節點由左至右是沒有空隙的,所以我們可以利用array 或者vector來儲存所有的節點。

堆演算法在標頭檔案algorithm中實現,主要操作有:push_heap演算法,pop_heap演算法,sort_heap演算法和make_heap演算法,一下以最大堆為例子,逐一介紹:

stl中堆的應用:

建堆 make_heap(_first,_last,_comp)

預設建立最大堆,如果要建小跟堆要在比較函式中打大於號(>),注意,是大於號

在堆中新增資料

push_heap(_first,_last)

要現在容器中加如資料,再呼叫push_heap();

在堆中刪除資料

pop_heap(_first,_last)

要先呼叫pop_heap(),再在容器中刪除資料;

堆排序

sort_heap(_first,_last,)

排序後就不是乙個合法的堆了,堆排序大家應該都懂吧

//待完善

#include

#include

#include

using

namespace

std;

void print_ivec(vector

::iterator begin, vector

::iterator end)

//建立最小堆的比較函式

bool cmp(int a,int b)

int main(int argc, char* argv)

; vector

ivec(a, a + sizeof(a) / sizeof(a[0]));

print_ivec(ivec.begin(), ivec.end());

//建堆 最小堆

make_heap(ivec.begin(), ivec.end(),cmp);

print_ivec(ivec.begin(), ivec.end());

//在堆中刪除元素

pop_heap(ivec.begin(), ivec.end(),cmp);

ivec.pop_back();

print_ivec(ivec.begin(), ivec.end());

//在堆中新增元素

ivec.push_back(0);

push_heap(ivec.begin(), ivec.end(),cmp);

print_ivec(ivec.begin(), ivec.end());

//排序 為什麼需要加入比較函式。。。不加會報錯。。。

sort_heap(ivec.begin(), ivec.end(),cmp); //但是此時就破壞了堆

print_ivec(ivec.begin(), ivec.end());

return

0;}

左傾堆的C 實現

在下小白乙個 如有錯誤請指正 上 using system 資料結構 namespace datastructure public leftistnoderightnode public t key public int npl public leftistnode leftistnodeleftn...

C 實現堆類

heap.hpp ifndef heap hpp define heap hpp template class t class heap template class t heap heap template class t heap heap int capacity template class...

c 對堆的簡單實現

include using namespace std typedef class poinner on class poinner on create int maxsize bool isempty on head bool isfull on head void insert on head,...