Heap
Heap 定義
A heap T is a complete binary tree in which either T is empty or
- left child is less than or equal to root
- right child is greater than or equal to root
- 適合用 array 來實作,root為 i(index),left child = 2i+1 and right child = 2i+2
- Heap is a ordered Binary tree
- 適合 implements Priority Queue
註:前三點為 Max Heap
註:complete binary tree 只能最下最右的兒子缺少,index需與 full binary tree一樣
Heap介紹
以下程式碼解法根據台大研究所計算機概論考古題來解題
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
Heapify
pseudocode
用來檢查Heap是否滿足Max Heap or Min Heap ( root>left && root>right )
- Init: int i=0; int l=2i+1; int r=2i+2; int large=i;
- 比較root是否比left小,且left小於n,若是large = l;
- 比較root是否比right小,且right小於n,若是large = r;
- 檢查 i != large, then swap A[i] and A[large]
- recursive heapify(arr,n,large)
Insert element
pseudocode
- add node on the last of array
- compare with its father node, if newNode > father then swap
- while ( node = root || node < father )
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
Delete root
pseudocode
- swap root and the node on the last of array
- remove root(now on the last of array)
- compare the newRoot to others, if newRoot is smaller then swap => Heapify newRoot
- while do step 3
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
相關文章:HeapSort