Lecture 14 - Heap Sort-1
Lecture 14 - Heap Sort-1
12 16
1 4 7
19 12 16 1 4 7
Array A
Heap
• The root of the tree A[1] and given index i of a node, the
indices of its parent, left child and right child can be computed
PARENT (i)
return floor(i/2)
LEFT (i)
return 2i
RIGHT (i)
return 2i + 1
Heap order property
• For every node v, other than the root, the key stored in v is
greater or equal (smaller or equal for max heap) than the key
stored in the parent of v.
12 16
1 4 7
19 12 16 1 4 7
Array A
Min heap example
1
4 16
7 12 19
1 4 16 7 12 19
Array A
Heap Sort
• Array Representation of Binary Tree
• Complete Binary Tree
• Heap
• Insert
• Delete
• Heap Sort
• Heapify
9
Heap
10
Binary Tree
• Binary Tree is defined as a tree data structure where each node has at
most 2 children. Since each element in a binary tree can have only 2
children, we typically name them the left and right child.
11
Complete Binary Tree
• A complete binary tree is a special type of binary tree where all the
levels of the tree are filled completely except the lowest level nodes
which are filled from as left as possible.
• Height of complete Binary Tree is minimum (log n).
12
Complete Binary Tree?
13
Heap is a complete binary tree
14
Insertion
15
Insert 60
16
17
18
• Time taken for Insertion depends on number of swaps.
• Swaps depend on height of tree i.e. log n
• Minimum O(1) to O(log n)
19
Deletion
• Start from Root
20
Insert last element at root
21
• After insertion last element at root—Is tree Max
heap???
• Complexity is O(log n) –depending on height of tree.
22
23
1. Create Heap
24
Heapify
25
26
Heapify
27
Analysis
• Insertion – n elements taken n time for Binary Tree
• Insert a element in Heap – log n (depend on height)
• Total – O(nlogn)
28
2. Deletion
29
Analysis
• Deletion
• Deleting n elements – n
• Heapify – (log n)
Total – O(nlog)
Combined
Insertion and Deletion
n logn + n logn = 2nlog n = O(nlogn)
30
Heapify
31
32
33
• Heapify takes time O(n)
34
35
36