You are on page 1of 8

Priority Queues and

Binary Heap
Priority Queue
• A Priority Queue removes items based on a priority instead of
the order in which they were added to the queue
• This allows an item that has higher priority to move ahead of
others in line that have lower priority
• Ensuring that High priority items go first means that low
priority items might never get selected if higher priority items
are continuously added to the Priority Queue.
• The priority for Items in the Queue can be increased the
longer they are in the queue so that all items eventually get
serviced.
Priority Queue Methods

• Insert (item, priority) – Adds the item to the next open


position in the array and percolates it up as long as the parent
is lower priority.
• Maximum() - Returns the highest priority item at position 0
leaving it in the queue.
• ExtractMax() – Removes and returns the highest priority item
at position 0 and rebuilds the heap.
Binary Heap
• A Binary Heap is a balanced binary tree with a property called
Heap that puts the largest element at the root
• The Heap property makes the data structure good for a
Priority Queue in which the highest priority item is the first to
be removed from the Priority Queue regardless of when it
was added to the Queue
• Since the tree is balanced, it can be represented with an array
data structure where the parent node for index i is found at
index (i -1)/2, the left child is found at index 2i +1, and the
right child is found at index 2i + 2 (for 0 index based arrays)
Heap Property
• The Heap Property uses an algorithm to keep the largest
element in the root position of the tree (index 0 in the array)
• Think of the heap as a pile with the largest item always sitting
on top
• The other elements in the array follow the rule that the
parent will always be larger than the children but the left child
can be either bigger or smaller than the right child (unlike the
Binary Search Tree)
• To add an element, we place it in the last open position in the
array and then heapify it by replacing it with its parent while
the parent is smaller. If it is the largest element in the heap, it
will bubble all the way to the top to the root position.
Binary Heap Example
The binary heap shown below has 9 elements index value
and can be represented with an array as shown 0 100
on the right. For each element: 1 19
Parent = (index – 1) / 2
2 36
Left Child = 2*index + 1
Right Child = 2 * index + 2 3 17
A balanced tree of height h has 2h -1 elements 4 3
5 25
6 1
7 2
8 7
9
10
11
12
13
14
Heapify Algorithm
• Heapify is an algorithm that builds a heap by visiting each
internal node and percolating the larger values towards the
top (or percolating the smaller values towards the bottom)
• Multiple ways to do this but typically a function is called for all
the internal nodes to build the heap from the bottom by
checking each child and moving the largest value up if larger
than the parent.
Hard work pays

You might also like