STL原始碼分析之大頂堆

2021-07-03 03:52:46 字數 2003 閱讀 6890

關於大頂堆和小頂堆這裡就不再介紹了,這裡通過stl再次回顧一下。

heap為了適應容器大小的不斷變化,底層呼叫vector實現

關於heap的演算法(這裡是大頂堆)

push_heap()演算法

為了滿足完全二叉樹的條件,新加入的元素一定是放在最下一層作為葉節點,並填補在由左至右的第乙個空格,即插在vector的end()處

我們通過上溯,將新節點與其父節點進行比較,如果鍵值比父節點的大,就對換位置,如此一直上溯,直到不需要對換或到了根節點為止。

以下即為push_heap的原始碼,兩個迭代器表示heap底部容器(array或vector)的頭尾,並且新的元素已經插入到底部容器的最尾端了。

template inline voidpush_heap(randomaccessiterator first, randomaccessiterator last) 

template inline void__push_heap_aux(randomaccessiterator first,

randomaccessiterator last, distance*, t*)

//上面為了處理

//不管上面的內容,我們只要知道holeindex就是插入的新節點在array/vector中的下標位置

template void__push_heap(randomaccessiterator first, distance holeindex,

distance topindex, t value)

//最後將這個指向新址的變數交給當前處理結束的節點

*(first + holeindex) = value;

}

pop_heap()演算法該操作取走根節點,即將整個堆最大的元素取走(其實是將此節點與整個堆的最後乙個元素交換位置),然後進行下溯操作,調整整棵樹

//這裡我們只看核心部分

template inline void__pop_heap(randomaccessiterator first, randomaccessiterator last,

randomaccessiterator result, t value,distance*)

template void__adjust_heap(randomaccessiterator first, distance holeindex,

distance len, t value)

//如果沒有右子,也能說明是走到最後了,因為是完全二叉樹嘛

if (secondchild == len)

__push_heap(first, holeindex, topindex, value);

}

make_heap()演算法即將乙個無序的陣列轉化為heap形式

template inline voidmake_heap(randomaccessiterator first, randomaccessiterator last) 

template void__make_heap(randomaccessiterator first, randomaccessiterator last,

compare comp, t*, distance*)

}

堆排序之 大頂堆

堆的定義 設有n個元素的序列 1 2 解釋 如果讓滿足以上條件的元素序列 建堆的步驟 從最後乙個非終端結點開始往前逐步調整,讓每個雙親大於 或小於 子女,直到根節點為止。注意 終端結點 即葉子 沒有任何子女,無需單獨調整。建堆的具體做法 1 將原始序列轉換成完全二叉樹。2 從序號最大的非葉子節點開始...

騷氣的Python之大頂堆演算法

大頂堆是一種結合二叉樹的排序演算法,平均時間複雜度為 nlogn 不清楚該演算法的可以先看詳細的介紹 coding utf 8 class heaptree object leftchild none rightchild none value none 排好順序的節點設定不可訪問 visitabl...

STL原始碼分析set

include include using namespace std int main set iset ia,ia 5 cout size iset.size endl cout 3 count iset.count 3 endl iset.insert 3 cout size iset.siz...