Heaps_Revised
Heaps_Revised
Trees
1 Heaps
3 Heap Algorithms
4 Heap Sort
Priority Queue Implementation
1 2 3 4 5 6 7
1. Add the element to the bottom level of the heap at the most
left.
2. Compare the added element with its parent; if they are in the
correct order, stop.
3. If not, swap the element with its parent and return to the
previous step.
Left (A , i )
1. if 2 * i ≤ heap - size [ A ]
2. return 2 * i
3. else
4. return NULL
Right (A , i )
1. if 2 * i + 1 ≤ heap - size [ A ]
2. return 2 * i + 1
3. else
4. return NULL
Heap - Sort ( A )
1. Build - Max - Heap ( A )
2. for i = length [ A ] down to 2
3. exchange A [1] and A [ i ]
4. heap - size [ A ] ← heap - size [ A ] - 1
5. Max - Heapify (A , 1)
8 3 6
6 4 6 4 3 4
5 1 3 5 1 5 1
6 1 5
5 4 5 4 1 4
3 1 3 3
5 1 4 and so on...
3 4 3 4 3 1
1
Output: 8, 6, 5, 4, 3, 1
Key
item
Data
Unordered Array/List
• Insert operation = O(1)
• Remove Max or Remove Min operation: O(n)
Ordered Array/List
• Insert operation = O(n)
• Remove Max or Remove Min operation: O(1)
We, however, do not need any operation to cost O(n) and rather
need more balanced approach where both insertion and
remove max (or min) operation takes O(log n) time.