Professional Documents
Culture Documents
2..2 Priorty Queue
2..2 Priorty Queue
2..2 Priorty Queue
Priority Queue can be used for load balancing and interrupt handling in an
operating system
DR. SHWETA SHARMA, PEC CHANDIGARH 2
Priority Queue vs. Normal Queue
In a Min Heap, the key at the root must be minimum or equal among all keys
present in Binary Heap. The tree must be a complete binary tree
Value (Parent) ≤ Children
In a Max Heap, the key at the root must be maximum among all keys present in
Binary Heap. The tree must be a complete binary tree.
Value (Parent) > Children
45 31 20 14 7 12 18 11 7
Its left child can be accessed by Ar[2 * i] and its right child can be
accessed by Ar[2 * i +1]
Index of root will be 1 in an array
1 BUILD-MAX-HEAP (A)
2 for i= A.length down to 2
3 exchange A[1] with A[i]
4 A.heapsize = A.heapsize – 1
5 MAX_HEAPIFY (A,1)
1 A.heapsize = A.length
𝐴.𝑙𝑒𝑛𝑔𝑡ℎ
2 for i= down to 1
2
3 MAX-HEAPIFY (A,i)
1 l = LEFT(i)
2 r = RIGHT(i)
3 if l ≤ A.heapsize and A[l] > A[i]
4 Largest = l
5 else largest = i
6 if r ≤ A.heapsize and A[r] > A[largest]
7 largest = r
8 if largest ≠ i
9 Excahnge A[i] with A[largest]
10 MAX-HEAPIFY (A,largest)
DR. SHWETA SHARMA, PEC CHANDIGARH 16
Example 1
Suppose you have 7 elements stored in array Arr.
Create a Max Heap
Max Heap:
HEAPSORT (A)
1 BUILD-MAX-HEAP (A)
2 for i= A.length down to 2
3 exchange A[1] with A[i]
4 A.heapsize = A.heapsize – 1
5 MAX_HEAPIFY (A,1)
HEAPSORT (A)
1 BUILD-MAX-HEAP (A)
2 for i= A.length down to 2
3 exchange A[1] with A[i]
4 A.heapsize = A.heapsize – 1
5 MAX_HEAPIFY (A,1)
HEAPSORT (A)
1 BUILD-MAX-HEAP (A)
2 for i= A.length down to 2
3 exchange A[1] with A[i]
4 A.heapsize = A.heapsize – 1
5 MAX_HEAPIFY (A,1)
HEAPSORT (A)
1 BUILD-MAX-HEAP (A)
2 for i= A.length down to 2
3 exchange A[1] with A[i]
4 A.heapsize = A.heapsize – 1
5 MAX_HEAPIFY (A,1)
Sorted Array
Time Complexity
Best Ω (nlogn)
Worst O (nlogn)
Average Θ (nlogn)
1, 5, 6, 8, 12, 14, 16