Binary Heaps: - Order Property: Key (Parent) Key (Child) (Minimum or Maximum Property)
Binary Heaps: - Order Property: Key (Parent) Key (Child) (Minimum or Maximum Property)
Binary Heaps: - Order Property: Key (Parent) Key (Child) (Minimum or Maximum Property)
77 46
69 3 11
5 6
15 9 7 20
16 25 14 12 11 8
1
1
Height of a Heap
Array representation of Heaps
1 45
• Because the structure of a
• A heap T storing n 2 3
keys has height complete binary tree is so 42 23
regular, a Heap can be
h = log(n + 1), represented in an array
4 5 6 7
27 35 22 6
which is O(log n) without using pointers
8 9 10
• Index the nodes as shown: 19 5 21
1 2 3 4 5 6 7 8 9 10
45 42 23 27 35 22 6 19 5 21
The left node of the node at index i is at index 2i, the right node is at index
(2i+1), and the parent is at index i/2 , so tree traversal is very easy
Inserting in HEAP
7 8
2
2
Inserting into a Heap Inserting into a Heap (contd.)
35 23 19 5 42 19 5 21
Insert 42 into this heap:
27 21 22 6
Create a node for 42 in the first Swap 42 with its parent node
available place
19 5
9 10
Heap Insertion
Inserting into a Heap (contd.)
• The key to insert is 6
45
Note that, since the largest
element is always at the root, a
42
35 23 heap makes an ideal structure
with which to implement a
27 35
42 22 6 priority queue
19 5 21
11
3
3
Heap Insertion Upheap
• Swap parent-child keys out of order
• Upheap terminates when new key is greater than the key of its
parent or the top of the heap is reached
• (total #swaps) = Order of height (h), which is O(log n)
4
4
Insheap(Tree,N,Item)
• Build a heap from list
44 30 50 22 60 55 77 55 Heap H with N elements is stored in array TREE and item of
information is given. PTR gives location of ITEM as it rises
in TREE and PAR denotes location of Parent of ITEM.
1. [Add new node to H and initialize PTR]
Set N=N+1 and PTR=N
2. [Find location to insert ITEM]
Repeat steps 3 to 6 while PTR<1
3. Set Par:=PTR/2 {location of parent node]
4. It Item<= Tree[Par] then Set Tree[PTR]=Item and return
5. Set Tree[PTR]:= Tree[PAR] [ Moves node down]
6. Set PTR=PAR [updates PTR] [end loop]
7. [Assign Item as root of H]
Set Tree[1]=Item
17 18
Return
5
5
Downheap Continues Downheap Continues
6
6
Heap Sort(A,N)
1. Build a heap H using previous procedure
Repeat for J= 1 to N-1 Call INSHEAP(A,J,A[j+1])
2. [Sort A repeatedly deleting root of H using Procedure 7.10]
Repeat while N >1
1. Call DELHEAP(A,N,ITEM)
2. Set A[N+1 ] =ITEM
Exit.
Complexity:
Phase A: number of comparisons to find appropriate place of
new ITEM cannot exceed depth ie log 2n. Therefore total
num of comparisons to insert n elements is g(n) <=n log 2n
Phase B: Re-heaping uses 4 comparisons to move node one step
down the tree. Therefore total num h(n) of comparisons to
delete n elements of A from H h(n) <= 4 .n. log 2n
that means over-all complexity is O(n. log 2n). 25
7
7