Heap Sort in C++
Heap Sort in C++
Heap Sort in C++
Fall 2023
4
10
19
5 3
13 8
11 22
insert()
deleteMin()
N=10
Every level
(except last)
saturated
• Min-Heap property
– Key associated with the root is less than or equal to the keys
associated with either of the sub-trees (if any)
– Both of the sub-trees (if any) are also binary min-heaps
• Properties of min-heap
– A single node is a min-heap
– Minimum key always at root
– For every node X, key(parent(X)) ≤ key(X)
– No relationship between nodes with similar key
• Min-Heap
Minimum
element
No relationship
• Max-Heap property
– Maximum key at the root
– For every node X, key(parent(X)) ≥ key(X)
• Insert new element into the heap at the next available slot (“hole”)
– Maintaining (almost) complete binary tree
• Percolate the element up the heap while heap-order property not
satisfied
• Insert 14
14 hole
• Insert 14
(1)
14 vs. 31
14
14 hole
• Insert 14
(2)
14 vs. 21 14
14
• Insert 14
(3)
14 vs. 13
14
Path of percolating up
Replace 13
with 31 here
Move 31 down
Delete this
node
Data Structures 18 - Heap Sort 15
deleteMin – Example
Copy 31 temporarily
here and move it down
Make this
position Is 31 > min(14,16)?
empty - Yes - swap 31 with min(14,16)
31
Is 31 > min(19,21)?
- Yes - swap 31 with min(19,21)
31
31
31
• deleteMin operation
– Replacing the top element is O(1)
– Percolate down the top object is O(log2 n)
– We copy something that is already in the lowest depth
It will likely be moved back to the lowest depth
Array representation:
i
2i + 1
i / 2 2i
Data Structures 18 - Heap Sort 21
Array-Based Implementation Of Binary Heap
i / 2
i / 2
Data Structures 18 - Heap Sort 24
Array-Based Implementation – insert
• Swap 8 and 12
• Removing the top require copy of the last element to the top
Nothing
to do
Swap with
left child
Nothing
to do
Swap
with right
child
Nothing
to do
Final Heap
• Algorithm:
– Build a heap from the given input array
Heapify all non-leaf nodes
– Repeat the following steps until the heap contains only one element
Swap the root element of the heap with the last element of the heap
Remove the last element of the heap
Heapify the remaining elements of the heap to maintain heap order
• Use max-heap for ascending sort and min-heap for descending sort