一個大小為n的堆是一棵包含n個結點的完全二叉樹, 該樹中每個結點的關鍵字值大于等于其雙親結點的關鍵字值.?
堆頂: 二叉樹的根, 它的關鍵字是整棵樹上最小的.(最小堆)
建堆運算時, CreatHeap()函數完成將一個以任意次序排列的元素排列, 通過向下調整建成最小堆.
實現運算AdjustDown的方法是: 向下調整heap[r]. 設tmp = hear[r], 如果tmp大于其左, 右孩子中的較小者, 則將tmp與該較小元素交換,?
調整后繼續將tmp與它的左右孩子比較. 如果比較小的孩子大, 則繼續交換. 直到不需要再調整或者已經到堆底.
實現代碼:
~~~
#include "iostream"
#include "cstdio"
#include "cstring"
#include "algorithm"
using namespace std;
template <class T>
void AdjustDown(T heap[], int r, int j)
{
int child = 2 * r + 1;
T tmp = heap[r];
while(child <= j) {
if(child < j && heap[child] > heap[child + 1]) child++;
if(tmp < heap[child]) break;
heap[(child - 1) / 2] = heap[child];
child = 2 * child + 1;
}
heap[(child - 1) / 2] = tmp;
for(int i = 0; i <= j; ++i)
cout << heap[i] << "\t";
cout << endl;
}
template <class T>
void CreatHeap(T heap[], int n)
{
for(int i = (n - 2) / 2; i > -1; --i)
AdjustDown(heap, i, n - 1);
}
int main(int argc, char const *argv[])
{
int heap[] = {61, 28, 81, 43, 36, 47, 83, 5};
for(int i = 0; i < 8; ++i)
cout << heap[i] << "\t";
cout << endl;
CreatHeap(heap, 8);
return 0;
}
~~~
- 前言
- 線性表的順序表示:順序表ADT_SeqList
- 結點類和單鏈表ADT_SingleList
- 帶表頭結點的單鏈表ADT_HeaderList
- 堆棧的順序表示ADT_SeqStack
- 循環隊列ADT_SeqQueue
- 一維數組ADT_Array1D
- 稀疏矩陣ADT_SeqTriple
- 數據結構實驗1(順序表逆置以及刪除)
- 數據結構實驗1(一元多項式的相加和相乘)
- 二叉樹ADT_BinaryTree
- 優先隊列ADT_PrioQueue
- 堆ADT_Heap
- 數據結構實驗2(設計哈弗曼編碼和譯碼系統)
- ListSet_無序表搜索
- ListSet_有序表搜索
- ListSet_對半搜索的遞歸算法
- ListSet_對半搜索的迭代算法
- 二叉搜索樹ADT_BSTree
- 散列表ADT_HashTable
- 圖的鄰接矩陣實現_MGraph
- 圖的鄰接表實現_LGraph
- 數據結構實驗2(二叉鏈表實現二叉樹的基本運算)
- 數據結構實驗3(圖的DFS和BFS實現)
- 數據結構實驗3(飛機最少環城次數問題)
- 拓撲排序的實現_TopoSort
- 數據結構實驗4(排序算法的實現及性能分析)