Priority Queue Notes
Priority Queue Notes
Introduction
● Priority Queues are abstract data structures where each data/value in the
queue has a certain priority.
● A priority queue is a special type of queue in which each element is served
according to its priority.
● If elements with the same priority occur, they are served according to their
order in the queue.
● Generally, the value of the element itself is considered for assigning the
priority.
● For example, the element with the highest value is considered as the highest
priority element. However, in some cases, we may assume the element with
the lowest value to be the highest priority element. In other cases, we can set
priorities according to our needs.
1
Auxiliary Priority Queues Operations
● kth - Smallest/kth – Largest: Returns the kth -Smallest/kth –Largest key in
the priority queue.
● Size: Returns the number of elements in the priority queue.
● Heap Sort: Sorts the elements in the priority queue based on priority (key).
2
● Elements are inserted into the array in sorted order based on the key field.
Deletions are performed at only one end.
● Insertions complexity: O
(n); DeleteMin complexity: O
(1).
3
Heaps
● A heap is a tree with some special properties.
● The basic requirement of a heap is that the v
alue of a node must be ≥ (or ≤)
than the values of its children. This is called the h
eap property.
● A heap also has the additional property that all leaf nodes should be at h or
h – 1 level (where h is the height of the tree) for some h > 0 (complete binary
trees).
● That means the heap should form a complete binary tree (as shown below).
In the examples below, the left tree is a heap (each element is greater than its
children) and the right tree is not a heap (since 11 is greater than 2).
4
Types of Heaps
Based on the property of a heap we can classify heaps into two types:
● Min heap: The value of a node must be less than or equal to the values of its
children.
● Max heap: The value of a node must be greater than or equal to the values
of its children.
5
Binary Heaps
● In a binary heap, each node may have up to two children.
● In practice, binary heaps are enough and we concentrate on binary min
heaps and binary max heaps for the remaining discussion.
Representing Heaps: Before looking at heap operations, let us see how heaps can
be represented. One possibility is using arrays. Since heaps are forming complete
binary trees, there will not be any wastage of locations. For the discussion below let
us assume that elements are stored in arrays, which starts at index 0. The previous
max heap can be represented as:
Heap Operations
Some of the important operations performed on a heap are described below along
with their algorithms.
Heapify
Heapify is the process of creating a heap data structure from a binary tree. It is
used to create a Min-Heap or a Max-Heap.
6
● Create a complete binary tree from the array
● Start from first index of the non-leaf node whose index is given by n
/2 - 1.
7
● Swap largest w
ith currentElement. #Condition3
● Repeat steps 3-7 until the subtrees are also heapified.
● For Min-Heap, both l eftChild and rightChild must be smaller than the
parent for all nodes.
Java Code
public class Priority_Queue {
public Priority_Queue() {
heap = new ArrayList<>();
}
boolean isEmpty(){
return heap.size() == 0;
}
int size(){
return heap.size();
}
8
largest = l;
if (r < n && arr[largest] < arr[r]) #Condition2
largest = r;
if (largest!=i) {
int temp = heap.get(i);
heap.set(i, heap.get(largest));
heap.set(largest, temp);
heapify(largest);
}
}
}
9
Java Code
public void insert(int element) {
heap.add(element);
int childIndex = heap.size()-1;
int parentIndex = (childIndex-1)/2;
while(childIndex > 0) {
if(heap.get(parentIndex) < heap.get(childIndex)) {
int temp = heap.get(parentIndex);
heap.set(parentIndex, heap.get(childIndex));
heap.set(childIndex, temp);
childIndex = parentIndex;
parentIndex = (childIndex - 1)/2;
}
else {
break;
}
}
}
10
Java Code
public int removeMax() throws PriorityQueueException {
if(isEmpty()) {
throw new PriorityQueueException();
}
int retVal = heap.get(0);
heap.set(0, heap.get(heap.size()-1));
heap.remove(heap.size()-1);
if(heap.size() > 1) {
heapify(0);
}
return retVal;
}
11
Heap Sort
● Heap Sort is another example of an efficient sorting algorithm. Its main
advantage is that it has a great worst-case runtime of O
(nlog(n)) regardless
of the input data.
● As the name suggests, Heap Sort relies heavily on the heap data structure - a
common implementation of a Priority Queue.
● Without a doubt, Heap Sort is one of the simplest sorting algorithms to
implement, and coupled with the fact that it's a fairly efficient algorithm
compared to other simple implementations, it's a common one to encounter.
Algorithm
● The heap-sort algorithm inserts all elements (from an unsorted array) into a
maxheap.
● Note that heap sort can be done i n-place with the array to be sorted.
● Since the tree satisfies the 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 in the list are sorted.
Consider the given illustrated example:
-> Applying heapsort to the unsorted array [12, 6, 10, 5, 1, 9]
12
13
14
Go through the given Java Code for better understanding:
int n = input.length;
for (int i=n-1; i>=0; i--) {
// Move current root to end
int temp = input[0];
input[0] = input[i];
input[i] = temp;
15
heapify(input, 0, i);
}
}
if(largest!=index){
int k = input[index];
input[index] = input[largest];
input[largest] = k;
heapify(input, largest, arrLength);
}
}
● add– This function adds an element to the heap without altering the current
heap.
● remove- This function returns the smallest data element from the heap.
import java.util.PriorityQueue;
16
public class PriorityQueueUse {
public static void main(String[] args) {
For max heap you just need to change the initialisation with reverse order as shown
below:
17
Approach
● Build a min-heap of size n of all elements.
● Extract the minimum elements K
times, i.e. delete the root and perform
heapify operation K times.
● Store all these K smallest elements.
Note: T
he code written using these insights can be found in the solution tab of the
problem itself.
18