Max Heap, Min Heap, Heapify, Heap sort, Build max Heap

zeeshanmubeen1 55 views 20 slides Jan 12, 2025
Slide 1
Slide 1 of 20
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20

About This Presentation

Max Heap, Min Heap, Heapify, Heap sort


Slide Content

Heap (Max/ Min / Heapify ) Prepared By: Mr. Zeeshan Mubeen (Senior Lecturer, RSCI) Unit No. 10

What is a Heap? A Heap is a special Tree-based data structure in which the tree is a complete binary tree. It’s a complete tree (All levels are completely filled except possibly the last level and the last level has all keys as left as possible). Generally, Heaps can be of two types: Max Heap Min Heap

Max Heap: In a Max-Heap the key present at the root node must be greatest among the keys present at all of it’s children. The same property must be recursively true for all sub-trees in that Binary Tree.

Min Heap: In a Min-Heap the key present at the root node must be minimum among the keys present at all of it’s children. The same property must be recursively true for all sub-trees in that Binary Tree.

Traversal Method: The traversal method use to achieve Array representation is Level Order Arr [(i-1)/2] Returns the parent node Arr [(2*i)+1] Returns the left child node Arr [(2*i)+2] Returns the right child node Below table shows indexes of other nodes for the i th node, i.e., Arr [i]:

Build Max Heap Build Max-Heap : Using MAX-HEAPIFY() we can construct a max-heap by starting with the last node that has children (which occurs at A.length /2 the elements the array A. BUILD-MAX-HEAP(A) A.heapsize = A.length for i = A.length /2 downto MAX-HEAPIFY( A,i )

Max- Heapify : Max- Heapify : Given a tree that is a heap except for node i,Max-Heapify function arranges node i and it’s subtrees to satisfy the heap property.

Build max Heap:

Build max Heap….

Build max Heap….

Build max Heap….

Heap Sort:

Heap Sort….

Heap Sort….

Heap Sort….

Heap Sort….

Heap Sort….

Heap Sort….

Heap Sort….

How Heap Sort Works? Since the tree satisfies Max-Heap property, then the largest item is stored at the root node. Swap: Remove the root element and put at the end of the array (nth position) Put the last item of the tree (heap) at the vacant place. Remove: Reduce the size of the heap by 1. Heapify : Heapify the root element again so that we have the highest element at root. The process is repeated until all the items of the list are sorted.