Priority Queue
A Priority Queue is a special type of queue where each element has a priority. Elements with higher priority are served before elements with lower priority. In Java, we can use the built-in PriorityQueue class. By default, it implements a Min-Heap (smallest element is processed first).
Code Example
JavaPythonCC++
import java.util.PriorityQueue;
public class PriorityQueueDemo {
public static void main(String[] args) {
// Min Heap (Default behavior)
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
minHeap.add(30);
minHeap.add(10);
minHeap.add(20);
System.out.println("Processing Min Heap:");
while (!minHeap.isEmpty()) {
// poll() removes the head of the queue (smallest element)
System.out.println(minHeap.poll());
}
// Output: 10, 20, 30
// Max Heap (Custom Comparator)
PriorityQueue<Integer> maxHeap = new PriorityQueue<>((a, b) -> b - a);
maxHeap.add(30);
maxHeap.add(10);
maxHeap.add(20);
System.out.println("\nProcessing Max Heap:");
while (!maxHeap.isEmpty()) {
System.out.println(maxHeap.poll());
}
// Output: 30, 20, 10
}
}
import heapq
# Min Heap (Default behavior)
minHeap = []
heapq.heappush(minHeap, 30)
heapq.heappush(minHeap, 10)
heapq.heappush(minHeap, 20)
print("Processing Min Heap:")
while minHeap:
print(heapq.heappop(minHeap))
# Output: 10, 20, 30
# Max Heap (Using negative values)
maxHeap = []
heapq.heappush(maxHeap, -30)
heapq.heappush(maxHeap, -10)
heapq.heappush(maxHeap, -20)
print("\nProcessing Max Heap:")
while maxHeap:
print(-heapq.heappop(maxHeap))
# Output: 30, 20, 10
#include <stdio.h>
#include <stdlib.h>
#define SIZE 100
int heap[SIZE];
int n = 0;
// Insert into Min Heap
void insert(int value) {
int i = n++;
heap[i] = value;
while (i != 0 && heap[(i - 1) / 2] > heap[i]) {
int temp = heap[i];
heap[i] = heap[(i - 1) / 2];
heap[(i - 1) / 2] = temp;
i = (i - 1) / 2;
}
}
// Extract Min
int extractMin() {
if (n <= 0) return -1;
int root = heap[0];
heap[0] = heap[--n];
int i = 0;
while (1) {
int left = 2 * i + 1;
int right = 2 * i + 2;
int smallest = i;
if (left < n && heap[left] < heap[smallest])
smallest = left;
if (right < n && heap[right] 0) {
printf("%d\n", extractMin());
}
return 0;
}
#include <iostream>
#include <queue>
using namespace std;
int main() {
// Min Heap (Default behavior)
priority_queue<int, vector<int>, greater<int>> minHeap;
minHeap.push(30);
minHeap.push(10);
minHeap.push(20);
cout << "Processing Min Heap:" << endl;
while (!minHeap.empty()) {
cout << minHeap.top() << endl;
minHeap.pop();
}
// Max Heap
priority_queue<int> maxHeap;
maxHeap.push(30);
maxHeap.push(10);
maxHeap.push(20);
cout << "\nProcessing Max Heap:" << endl;
while (!maxHeap.empty()) {
cout << maxHeap.top() << endl;
maxHeap.pop();
}
return 0;
}