3_HeapSort
3_HeapSort
Heap Sort
O(n log n)
In-Place sorting
Heap Sort
• Heap sort is an O(nlogn) comparison based in-place sorting
algorithm.
• Heap sort is not a stable sorting algorithm.
• Heap sort uses a Heap data structure.
• Heap data structure is also used in priority queue.
Heaps
Tree based data structure
Why Heaps?
• There are many data structures which can perform operations such as
search, insert, delete, findMin, findMax etc.
• But every data structure optimizes any one ot few of these
operations.
• Linked list: Insertion/deletion takes O(1), whereas searching takes
O(n)
• Array: Insertion/deletion takes O(n) but searching takes O(1)
• We want a DS which can optimize most of these operations.
Why Heaps?
• Job scheduler
• Priority queue
• Event driven simulator
10
21 39
43 80 86
Heap Sort
O(n log n)
In-Place sorting
Heap Sort
Construct a Max-Heap
Largest value of the array is at root Put the largest value at the end of that array.
1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10
16 14 10 8 7 9 3 2 4 1 1 14 10 8 7 9 3 2 4 16
Heap sort:
Example
Heap Sort: Algorithm
• What will be the running time of heapsort on an array of
length n that is already sorted in increasing order.