← Back to DSA Course | Chapter 6: Queues | Lesson 5 of 5

Priority Queue क्या है

एक priority queue एक emergency room जैसी है: patients को देखा जाता है इस आधार पर कि वे कितने urgent हैं, कौन पहले आया इसके आधार पर नहीं।
Syntax
markup
import heapq
heap = []
heapq.heappush(heap, (priority, item))
priority, item = heapq.heappop(heap)

What is a Priority Queue?

एक priority queue एक data structure है जहां elements उनकी priority के अनुसार बाहर आते हैं, वे कितनी देर से इंतज़ार कर रहे हैं इसके अनुसार नहीं, एक regular FIFO queue के विपरीत।

उदाहरण: What is a Priority Queue?

#include <iostream>
#include <queue>
using namespace std;
int main() {
	priority_queue<int> pq;
	pq.push(3); pq.push(10); pq.push(1);
	cout << "Highest priority: " << pq.top();
	return 0;
}
import java.util.*;
public class Main {
	public static void main(String[] args) {
		PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
		pq.add(3); pq.add(10); pq.add(1);
		System.out.println("Highest priority: " + pq.peek());
	}
}
import heapq
pq = []
for v in (3, 10, 1):
    heapq.heappush(pq, -v)
print("Highest priority:", -pq[0])
#include <stdio.h>
int main() {
	int arr[] = {3, 10, 1};
	int maxVal = arr[0];
	for (int i = 1; i < 3; i++) if (arr[i] > maxVal) maxVal = arr[i];
	printf("Highest priority: %d", maxVal);
	return 0;
}

Insert Priority Elements

Elements किसी भी दूसरी structure की तरह insert किए जाते हैं, लेकिन priority queue internally खुद को reorganize करता है (आमतौर पर एक heap उपयोग करते हुए) ताकि यह हमेशा जाने कि अभी किस element की सबसे ज़्यादा, या सबसे कम, priority है।

उदाहरण: Insert Priority Elements

#include <iostream>
#include <queue>
using namespace std;
int main() {
	priority_queue<int> pq;
	pq.push(5); pq.push(20); pq.push(15);
	cout << "Top after inserts: " << pq.top();
	return 0;
}
import java.util.*;
public class Main {
	public static void main(String[] args) {
		PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
		pq.add(5); pq.add(20); pq.add(15);
		System.out.println("Top after inserts: " + pq.peek());
	}
}
import heapq
pq = []
for v in (5, 20, 15):
    heapq.heappush(pq, -v)
print("Top after inserts:", -pq[0])
#include <stdio.h>
int main() {
	int arr[] = {5, 20, 15};
	int maxVal = arr[0];
	for (int i = 1; i < 3; i++) if (arr[i] > maxVal) maxVal = arr[i];
	printf("Top after inserts: %d", maxVal);
	return 0;
}

Remove by Priority

Priority queue से हटाना हमेशा current highest-priority element (एक max-priority queue में) या lowest-priority element (एक min-priority queue में) return करता है, जो इसे एक plain queue के strict arrival order से अलग करता है।

उदाहरण: Remove by Priority

#include <iostream>
#include <queue>
using namespace std;
int main() {
	priority_queue<int> pq;
	pq.push(5); pq.push(20); pq.push(15);
	while (!pq.empty()) { cout << pq.top() << " "; pq.pop(); }
	return 0;
}
import java.util.*;
public class Main {
	public static void main(String[] args) {
		PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
		pq.add(5); pq.add(20); pq.add(15);
		while (!pq.isEmpty()) System.out.print(pq.poll() + " ");
	}
}
import heapq
pq = []
for v in (5, 20, 15):
    heapq.heappush(pq, -v)
while pq:
    print(-heapq.heappop(pq), end=" ")
#include <stdio.h>
int main() {
	int arr[] = {20, 15, 5};
	for (int i = 0; i < 3; i++) printf("%d ", arr[i]);
	return 0;
}

Priority Queue Applications

Priority queues CPU task scheduling (सबसे urgent job पहले चलाना), Dijkstra के shortest path algorithm (हमेशा सबसे करीब unvisited node अगला expand करना), और event-driven simulations जो events को time order में process करते हैं उनके लिए ज़रूरी हैं।

उदाहरण: Priority Queue Applications

#include <iostream>
#include <queue>
#include <string>
using namespace std;
int main() {
	priority_queue<pair<int, string>> pq;
	pq.push({2, "Print doc"}); pq.push({5, "Fix server outage"}); pq.push({1, "Reply email"});
	cout << "Next task: " << pq.top().second;
	return 0;
}
import java.util.*;
public class Main {
	public static void main(String[] args) {
		PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> b[0] - a[0]);
		pq.add(new int[]{2, 0}); pq.add(new int[]{5, 1}); pq.add(new int[]{1, 2});
		String[] tasks = {"Print doc", "Fix server outage", "Reply email"};
		System.out.println("Next task: " + tasks[pq.peek()[1]]);
	}
}
import heapq
tasks = [(-2, "Print doc"), (-5, "Fix server outage"), (-1, "Reply email")]
heapq.heapify(tasks)
print("Next task:", tasks[0][1])
#include <stdio.h>
int main() {
	char *tasks[] = {"Print doc", "Fix server outage", "Reply email"};
	int priority[] = {2, 5, 1};
	int best = 0;
	for (int i = 1; i < 3; i++) if (priority[i] > priority[best]) best = i;
	printf("Next task: %s", tasks[best]);
	return 0;
}

Priority Queue Practice

Max-priority और min-priority variants को साथ-साथ काम करना distinction को concrete बनाता है: underlying operations identical हैं, सिर्फ priority decide करने के लिए उपयोग होने वाला comparison flipped है।

उदाहरण: Priority Queue Practice

#include <iostream>
#include <queue>
using namespace std;
int main() {
	priority_queue<int> maxPQ;
	priority_queue<int, vector<int>, greater<int>> minPQ;
	for (int v : {4, 1, 7}) { maxPQ.push(v); minPQ.push(v); }
	cout << "Max: " << maxPQ.top() << ", Min: " << minPQ.top();
	return 0;
}
import java.util.*;
public class Main {
	public static void main(String[] args) {
		PriorityQueue<Integer> maxPQ = new PriorityQueue<>(Collections.reverseOrder());
		PriorityQueue<Integer> minPQ = new PriorityQueue<>();
		for (int v : new int[]{4, 1, 7}) { maxPQ.add(v); minPQ.add(v); }
		System.out.println("Max: " + maxPQ.peek() + ", Min: " + minPQ.peek());
	}
}
import heapq
values = [4, 1, 7]
min_pq = list(values)
heapq.heapify(min_pq)
max_pq = [-v for v in values]
heapq.heapify(max_pq)
print("Max:", -max_pq[0], ", Min:", min_pq[0])
#include <stdio.h>
int main() {
	int arr[] = {4, 1, 7};
	int maxVal = arr[0], minVal = arr[0];
	for (int i = 1; i < 3; i++) {
		if (arr[i] > maxVal) maxVal = arr[i];
		if (arr[i] < minVal) minVal = arr[i];
	}
	printf("Max: %d, Min: %d", maxVal, minVal);
	return 0;
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. यह उम्मीद करना कि एक priority_queue insertion order में items return करेगा, जब सबसे बड़ा पहले आता है।
  2. यह मान लेना कि priority_queue<int> एक min-heap है, जब एक min-heap को comparator के रूप में greater<int> चाहिए।
  3. एक priority queue को सीधे iterate करना, जो support नहीं किया जाता क्योंकि सिर्फ top() accessible है।
चैप्टर सारांश
  • एक queue first in, first out follow करता है और code में implement किया जा सकता है।
  • Circular queues और deques (double-ended queues) variations हैं जो यह बदलते हैं कि items कैसे जोड़े और हटाए जाते हैं।
  • एक priority queue arrival order के बजाय priority से items serve करता है।
🔒

Chapter Quiz — Complete all 5 topics to unlock

0/5 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.