7 Heaps
7 Heaps
HEAPS
DEFINITION
IMPLEMENTATION
Binary heaps are implemented using ARRAYS unlike Binary Search Trees and AVL
Trees.
The elements in a binary heap are indexed by LEVEL ORDER and from LEFT TO
RIGHT.
University of the Philippines Open University
CMSC 204: Data Structures and Algorithms
REMEMBER THESE
1. The parent of j is indexed L j/2 ˩ (i.e. floor function, ex. 5/2 is 2.5 and the
floor is 2)
2. The right child of j is indexed 2j+1
3. The left child of j is indexed 2j
EXAMPLE
0 60 20 15 3 5 1 7
0 1 2 3 4 5 6 7
Root == heap[1] == 60
heap[3]; //node 15
parent of node 15 is heap[1] //heap[L 3/2 ˩]; 3/2 = 1.5, floor of 1.5 is 1
right child of node 15 is heap[7] //heap[2*3+1]; 2*3+1 = 6+1 = 7
left child of node 15 is heap[6] //heap[2*3]; 2*3 = 6
try the formula on the other elements in the heap
University of the Philippines Open University
CMSC 204: Data Structures and Algorithms
“Given a binary heap, when the value of one of the nodes is modified, this may
violate the heap property. In the heap, it is usually the root that is modified or
deleted. Once this happens, the heap property must be restored.”
1. Start from the root. Compare the node with its children. If the node is the
maximum, stop.
2. If the left child is the maximum, swap value of the left child with the value
of the parent node. Continue checking if the heap property still holds in the
left subtree (recursively).
3. If the right child is the maximum, swap the value of the right child with the
value of the parent node. Continue checking if the heap property still holds
in the right subtree (recursively).
NOTE: Inserting the new element will possibly destroy the heap property. Hence,
the heap must be restored after its insertion.
Steps:
One of the binary heaps major applications is the priority queue. A priority queue
is a queue wherein the element with the highest priority (or highest value) is
returned first.
This is easily done by returning or deleting the maximum from a binary heap.
Return maximum – Simply return the value found in heap[1] (the root)
Delete maximum – Exchange the values of heap[1] and heap[heapsize] (the first
and last values in the heap) and then perform the restore heap operation on
heapsize-1. (Percolate down!)
HEAPSORT
Steps:
Watch this:
https://www.youtube.com/watch?v=q7R_upR81FU
Try this:
http://visualgo.net/heap.html
Read:
Module 7 (Page69) of CMSC 204 Manual
1. What new knowledge about heaps is the most interesting for you?
2. How will you apply heaps?