Uploaded by Zarar Azwar Khalid

Heap Sort Algorithm Explained

advertisement
DATA STRUCTURES AND ALGORITHMS
HEAP SORT
Presented by:
1. Mehreen Fatima(18-CS-53)
2. Zarar Azwar Khalid(18-CS-28)
WHAT IS
HEAPS?
 Heaps are binary trees.
 Heaps are complete binary trees.
 In case of sorting two types of heaps…
 Min heap
 Max heap
WHAT IS MAX
HEAP?
 The parent should always greater than
its both child.
 A[PARENT(i)] ≥ A[i]
 Root Node is always greatest.
WHAT IS MIN
HEAP?
 The parent should always lesser than its
both child.
 A[PARENT(i)] ≤A[i]
 Root Node is always smallest.
HOW TO BUILD MAX
HEAP?
Build - Max - Heap ( A)
heap - size[ A]  length[ A];
for i  length[ A] / 2 downto 1
do Max - Heapify ( A, i );
HOW TO BUILD MAX
HEAP?
HOW TO BUILD MAX
HEAP?
HOW TO BUILD MAX
HEAP?
HOW TO BUILD MAX
HEAP?
HOW TO BUILD MAX
HEAP?
HOW TO BUILD MAX
HEAP?
HOW TO BUILD MAX
HEAP?
HOW TO BUILD MAX
HEAP?
HOW TO BUILD MAX
HEAP?
HOW TO BUILD MAX
HEAP?
HOW TO BUILD MAX
HEAP?
HEAP SORTING (ALGORITHM)
 Build a max-heap from the array
 Swap the root (the maximum element) with the last element in the array
 “Discard” this last node by decreasing the heap size
 Call MAX-HEAPIFY on the new root
 Repeat this process until only one node remains
HEAP SORT
HEAP SORT
HEAP SORT
16
HEAP SORT
HEAP SORT
HEAP SORT
16
14
HEAP SORT
HEAP SORT
HEAP SORT
16
14
10
HEAP SORT
HEAP SORT
HEAP SORT
16
14
10
9
HEAP SORT
HEAP SORT
16
14
10
9
8
HEAP SORT
HEAP SORT
HEAP SORT
16
14
10
9
8
7
HEAP SORT
HEAP SORT
HEAP SORT
16
14
10
9
8
7
4
HEAP SORT
HEAP SORT
16
14
10
9
8
7
4
3
HEAP SORT
HEAP SORT
16
14
10
9
8
7
4
3
2
HEAP SORT
Sorted Array:
16
14
10
9
8
7
4
3
2
1
RUNNING TIME:
 Intuitively:
 Running time of MAX-HEAPIFY is O(lgn)
 Can be written in terms of the height of the heap, as being O(h)
 Since the height of the heap is lgn
RUNNING TIME:
Download