12 Heap
Based on complete binary trees
Types¶
Type | Property |
---|---|
Min-Heap | \(v \le\) descendants |
Max-Heap | \(v \ge\) descendants |
Implementation¶
Array¶
- Root = 0
- Left Child = \(2i+1\)
Consider a node with index \(i\)
Node | Value |
---|---|
Root of entire tree | 0 |
Left Child | \(2i+1\) |
Right Child | \(2i+2\) |
Parent | \((i-1)/2\) |
Linked List¶
\[ \fbox{l} \fbox{data} \fbox{r} \fbox{parent} \notag \]
Insertion¶
- Find insertion point
- Store there
- Verify heap property
- if not satisfied, up bubbling
Deletion¶
- Remove the root element (We cannot remove a particular element)
- Replace node with the last node of the subtree
- Verify Heap property
- if not satisfied, down bubbling
Heapification¶
up/down heap bubbling
- compare 2 elements
- swap if condition is not satisfied
void maxHeapify(int[] a, int n, int i)
{
int largest = i, // assuming root is the largest
l = (2*i) + 1,
r = (2*i) + 2;
if(l<n && a[l]>a[largest])
largest = l;
if(r<n && a[r]>a[largest])
largest = r;
if(largest != i)
// swap root with largest node
swap(a[i], a[largest])
}
Applications¶
- Heap Sort
- Order Statistics
- Priority Queue
Priority Queue¶
- Max-Heap for max-priority queue
- Min-Heap for min-priority queue