2. HEAPS
A heap is a tree-based data structure that satisfies the heap property, where each
element is assigned a key value.
Types of Heaps :
1. MAX HEAP
root >= child
2. MIN HEAP
root <= child
Image source : Google Images
3. Priority Queues
Priority queues are similar to queue data structure that follow FIFO organization.
Difference : Logical order of the elements inside the queue.
Element with highest priority will be moved to the front.
Element lowest priority will move to the back.
vice-versa
Types of Priority Queues:
Max-priority Queue
Min-priority Queue
4. MIN PRIORITY QUEUE USING HEAPS
Min-Priority queues are implemented using Min-Heaps.
Each element has a priority or a key.
Supports following operations :
• INSERT(A, x) : insert an element x into queue A.
• DECREASE-KEY(A, x, k) : decrease the value of element x’s key to new value k.
• EXTRACT-MIN(A) : removes and return the element with smallest key.
• MINIMUM(A) : returns element of A with the smallest key.
5. PSEUDOCODE
MIN-HEAPIFY(A, i)
l = LEFT(i)
r = RIGHT(i)
if l ≤ A.heap-size and A[l] < A[i]
smallest = l
else
smallest = i
if r ≤ A.heap-size and A[r] < A[smallest]
smallest = r
if smallest ≠ i
exchange A[i] with A[smallest]
MIN-HEAPIFY(A, smallest)
6. PSEUDOCODE
INSERT(A, key)
A.heap-size = A.heap-size + 1
A[A.heap-size] = ∞
DECREASE-KEY(A, A.heap-size, key)
DECREASE-KEY(A, i, key)
if key > A[i]
error “new key larger than current key”
A[i] = key
while i > 1 and A[PARENT(i)] > A[i]
exchange A[i] with A[PARENT(i)]
i = PARENT(i)
7. MINIMUM(A)
return A[1] //root of the Heap
PSEUDOCODE
EXTRACT-MIN(A)
if A.heap-size < 1
error “heap underflow”
min = A[1]
A[1] = A[A.heap-size]
A.heap-size = A.heap-size - 1
MIN-HEAPIFY(A, 1)
return min
9. TIME COMPLEXITY
• INSERT(A, x)
• DECREASE-KEY(A, x, k)
• EXTRACT-MIN(A)
• MINIMUM(A)
O log 2 (N)
O log 2 (N)
O log 2 (N)
O (1)
COMPARISON WITH MAX-PIORITY QUEUEs
The running time is the same.
The algorithm is the same with the exceptions of two comparisons and some names.
**N = no. of inputs
10. In Naive Approach if we have N elements insertion and deletion from the list takes O(N) time.
To maintain the priority queue it take O(N log 2 N ) time.
In Heap implementation it will take O(log 2 N) time to insert and delete each element in the priority
queue.
Hence implementation using Heaps is a very Efficient Approach.
Applications:
Graph algorithms like Dijkstra’s shortest path algorithm etc.
Machine Scheduling
CONCLUSION