0% found this document useful (0 votes)
14 views14 pages

What Is Priority Queue - Introduction To Priority Queue

A priority queue is a specialized queue that orders elements based on their priority values, allowing higher priority elements to be processed before lower ones. It can be implemented using various data structures such as arrays, linked lists, heaps, or binary search trees, with binary heaps being the most common due to their efficiency. Priority queues are widely used in algorithms and real-time systems where processing order is determined by priority rather than arrival time.

Uploaded by

shallom.acquah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views14 pages

What Is Priority Queue - Introduction To Priority Queue

A priority queue is a specialized queue that orders elements based on their priority values, allowing higher priority elements to be processed before lower ones. It can be implemented using various data structures such as arrays, linked lists, heaps, or binary search trees, with binary heaps being the most common due to their efficiency. Priority queues are widely used in algorithms and real-time systems where processing order is determined by priority rather than arrival time.

Uploaded by

shallom.acquah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

What is Priority Queue | Introduction to Priority Queue

A priority queue is a type of queue that arranges elements based on their


priority values. Elements with higher priority values are typically retrieved or
removed before elements with lower priority values. Each element has a
priority value associated with it. When we add an item, it is inserted in a
position based on its priority value.
There are several ways to implement a priority queue, including using an
array, linked list, heap, or binary search tree, binary heap being the most
common method to implement. The reason for using Binary Heap is simple,
in binary heaps, we have easy access to the min (in min heap) or max (in
max heap) and binary heap being a complete binary tree are easily
implemented using arrays. Since we use arrays, we have cache friendliness
advantage also.
Priority queues are often used in real-time systems, where the order in
which elements are processed is not simply based on the fact who came
first (or inserted first), but based on priority. Priority Queue is used in
algorithms such as Dijkstra’s algorithm, Prim’s algorithm, Kruskal’s
algorithm and Huffnam Coding.

Properties of Priority Queue


So, a priority Queue is an extension of the queue with the following
properties.
Every item has a priority associated with it.
An element with high priority is dequeued before an element with low
priority.
If two elements have the same priority, they are served according to their
order in the queue.
In the below priority queue, an element with a maximum ASCII value will
have the highest priority. The elements with higher priority are served first.

How is Priority assigned to the elements in a Priority


Queue?
In a priority queue, generally, the value of an element is considered for
assigning the priority.
For example, the element with the highest value is assigned the highest
priority and the element with the lowest value is assigned the lowest
priority. The reverse case can also be used i.e., the element with the lowest
value can be assigned the highest priority. Also, the priority can be assigned
according to our needs.

Operations of a Priority Queue:


A typical priority queue supports the following operations:
1) Insertion in a Priority Queue

When a new element is inserted in a priority queue, it moves to the empty


slot from top to bottom and left to right. However, if the element is not in the
correct place then it will be compared with the parent node. If the element is
not in the correct order, the elements are swapped. The swapping process
continues until all the elements are placed in the correct position.

2) Deletion in a Priority Queue

As you know that in a max heap, the maximum element is the root node.
And it will remove the element which has maximum priority first. Thus, you
remove the root node from the queue. This removal creates an empty slot,
which will be further filled with new insertion. Then, it compares the newly
inserted element with all the elements inside the queue to maintain the
heap invariant.

3) Peek in a Priority Queue

This operation helps to return the maximum element from Max Heap or the
minimum element from Min Heap without deleting the node from the priority
queue.

Types of Priority Queue:

1) Ascending Order Priority Queue


As the name suggests, in ascending order priority queue, the element with a
lower priority value is given a higher priority in the priority list. For example, if
we have the following elements in a priority queue arranged in ascending
order like 4,6,8,9,10. Here, 4 is the smallest number, therefore, it will get the
highest priority in a priority queue and so when we dequeue from this type of
priority queue, 4 will remove from the queue and dequeue returns 4.

2) Descending order Priority Queue

The root node is the maximum element in a max heap, as you may know. It
will also remove the element with the highest priority first. As a result, the
root node is removed from the queue. This deletion leaves an empty space,
which will be filled with fresh insertions in the future. The heap invariant is
then maintained by comparing the newly inserted element to all other entries
in the queue.

Types of Priority Queues

Difference between Priority Queue and Normal Queue?


There is no priority attached to elements in a queue, the rule of first-in-first-
out(FIFO) is implemented whereas, in a priority queue, the elements have a
priority. The elements with higher priority are served first.

How to Implement Priority Queue?


Priority queue can be implemented using the following data structures:

Arrays
Linked list
Heap data
structure Binary
search tree

Let’s discuss all these in detail.

1) Implement Priority Queue Using Array:

A simple implementation is to use an array of the following structure.

struct item {
int item;
int
priority;
}

enqueue(): This function is used to insert new data into the queue.
dequeue(): This function removes the element with the highest priority from
the queue.
peek()/top(): This function is used to get the highest priority element in
the queue without removing it from the queue.

Arrays enqueue() dequeue() peek()

Time Complexity O(1) O(n) O(n)

C++ Java Python C# JavaScript

1 // C++ program to implement Priority


2
Queue
// using Arrays
3
#include <bits/stdc++.h>
4
using namespace std;
5
6 // Structure for the elements in
7 the
8
// priority queue
9
struct item {
10 int priority;
11 };
12
13 // Store the element of a priority queue
14 item pr[100000];
15
16 // Pointer to the last index
17 int size = -1;
18
19 // Function to insert a new element
20 // into priority queue
21 void enqueue(int value, int priority)
22 {
23 // Increase the size
24 size++;
25
26 // Insert the element
27 pr[size].value = value;
28 pr[size].priority = priority;
29 }
30
31 // Function to check the top element
32 int peek()
33 {
34 int highestPriority = INT_MIN;
35 int ind = -1;
36
37 // Check for the element with
38 // highest priority
39 for (int i = 0; i <= size; i++) {
40
41 // If priority is same choose
42 // the element with the
43 // highest value
44 if (highestPriority == pr[i].priority && ind > -
1
45 && pr[ind].value < pr[i].value) {
46 highestPriority = pr[i].priority;
47 ind = i;
48 }
49 else if (highestPriority < pr[i].priority) {
50 highestPriority = pr[i].priority;
51 ind = i;
52 }
53
}
54
55 // Return position of the element
56
return ind;
57 }
58

59 // Function to remove the element with


60 // the highest priority
61 void dequeue()
62 {
63 // Find the position of the element
64 // with highest priority
65 int ind = peek();
66
67 // Shift the element one index before
68 // from the position of the element
69 // with highest priority is found
70 for (int i = ind; i < size; i++) {
71 pr[i] = pr[i + 1];
72 }
73
74
// Decrease the size of the
75
// priority queue by one
76
size--;
77 }
78
79 // Driver Code
80 int main()
81 {
82 // Function Call to insert elements
83 // as per the priority
84 enqueue(10, 2);
85 enqueue(14, 4);
86 enqueue(16, 4);
87 enqueue(12, 3);
88
89 // Stores the top element
90 // at the moment
91 int ind = peek();
92
93 cout << pr[ind].value << endl;
94
95 // Dequeue the top element
96 dequeue();
97
98 // Check the top element
99 ind = peek();
100 cout << pr[ind].value <<
endl;
101
102 // Dequeue the top element
103 dequeue();
104
105 // Check the top element
106 ind = peek();
107 cout << pr[ind].value <<
endl;
108
109 return 0;
110 }

Output

16
14
12

2) Implement Priority Queue Using Linked List:

In a LinkedList implementation, the entries are sorted in descending order


based on their priority. The highest priority element is always added to the
front of the priority queue, which is formed using linked lists. The functions
like push(), pop(), and peek() are used to implement a priority queue using a
linked list and are explained as follows:
push(): This function is used to insert new data into the queue.
pop(): This function removes the element with the highest priority from
the queue.
peek() / top(): This function is used to get the highest priority element in
the queue without removing it from the queue.
Linked List push() pop() peek()

Time Complexity O(n) O(1) O(1)

C++ Java Python C# JavaScript

1 // C++ code to implement Priority Queue


2 // using Linked List
3 #include <bits/stdc++.h>
4 using namespace std;
5
6 // Node
7 typedef struct node {
8 int data;
9
10 // Lower values indicate
11 // higher priority
12 int priority;
13
14 struct node* next;
15
16 } Node;
17
18 // Function to create a new node
19 Node* newNode(int d, int p)
20 {
21 Node* temp = (Node*)malloc(sizeof(Node));
22 temp->data = d;
23 temp->priority = p;
24 temp->next = NULL;
25
26 return temp;
27 }
28
29 // Return the value at head
30 int peek(Node** head) { return (*head)- }
>data;
31
32 // Removes the element with the
33 // highest priority form the list
34 void pop(Node** head)

35 {
36 Node* temp = *head;
37 (*head) = (*head)->next;
38 free(temp);
39 }
40
41 // Function to push according to
priority
42 void push(Node** head, int d, int p)
43 {
44 Node* start = (*head);
45
46 // Create new Node
47 Node* temp = newNode(d, p);
48
49 // Special Case: The head of list
has
50 // lesser priority than new node
51 if ((*head)->priority < p) {
52
53 // Insert New Node before head
54 temp->next = *head;
55 (*head) = temp;
56 }
57 else {
58
59 // Traverse the list and find
a
60 // position to insert new node
61 while (start->next != NULL
62 && start->next->priority p) {
>
63 start = start->next;
64 }
65
66 // Either at the ends of the
list
67 // or at required position
68 temp->next = start->next;
69 start->next = temp;
70 }
71 }
72
73 // Function to check is list is empty
74 int isEmpty(Node** head) { return == NULL;
(*head) }
75
76 // Driver code
77 int main()

78 {
79
80 // Create a Priority Queue
81 // 7->4->5->6
82 Node* pq = newNode(4, 1);
83 push(&pq, 5, 2);
84 push(&pq, 6, 3);
85 push(&pq, 7, 0);
86
87 while (!isEmpty(&pq)) {
88 cout << " " <<
peek(&pq);
89 pop(&pq);
90 }
91 return 0;
92 }

Output

6 5 4 7

3) Implement Priority Queue Using Heaps:

Binary Heap is generally preferred for priority queue implementation because


heaps provide better performance compared to arrays or LinkedList.
Considering the properties of a heap, The entry with the largest key is on the
top and can be removed immediately. It will, however, take time O(log n) to
restore the heap property for the remaining keys. However if another entry is
to be inserted immediately, then some of this time may be combined with the
O(log n) time needed to insert the new entry. Thus the representation of a
priority queue as a heap proves advantageous for large n, since it is
represented efficiently in contiguous storage and is guaranteed to require
only
logarithmic time for both insertions and deletions. Operations on Binary Heap
are as follows:
insert(p): Inserts a new element with priority p.
extractMax(): Extracts an element with maximum priority.
remove(i): Removes an element pointed by an iterator i.
getMax(): Returns an element with maximum priority.
changePriority(i, p): Changes the priority of an element pointed by i to p.

Binary Heap insert() remove() peek()

Time Complexity O(log n) O(log n) O(1)

4) Implement Priority Queue Using Binary Search Tree:

A Self-Balancing Binary Search Tree like AVL Tree, Red-Black Tree, etc. can
also be used to implement a priority queue. Operations like peek(), insert()
and delete() can be performed using BST.

Binary Search Tree peek() insert() delete()

Time Complexity O(1) O(log n) O(log n)

Applications of Priority Queue:


CPU Scheduling
Graph algorithms like Dijkstra’s shortest path algorithm, Prim’s
Minimum Spanning Tree, etc.
All queue applications where priority is
involved. Data compression in Huffman code
Event-driven simulation such as customers waiting in a
queue. Finding Kth largest/smallest element.
Advantages of Priority Queue:
It helps to access the elements in a faster way. This is because elements in
a priority queue are ordered by priority, one can easily retrieve the highest
priority element without having to search through the entire queue.
The ordering of elements in a Priority Queue is done dynamically.
Elements in a priority queue can have their priority values updated,
which allows the queue to dynamically reorder itself as priorities
change.
Efficient algorithms can be implemented. Priority queues are used in many
algorithms to improve their efficiency, such as Dijkstra’s algorithm for
finding the shortest path in a graph and the A* search algorithm for
pathfinding.
Included in real-time systems. This is because priority queues allow you
to quickly retrieve the highest priority element, they are often used in real-
time systems where time is of the essence.

Disadvantages of Priority Queue:


High complexity. Priority queues are more complex than simple data
structures like arrays and linked lists, and may be more difficult to
implement and maintain.
High consumption of memory. Storing the priority value for each element
in a priority queue can take up additional memory, which may be a
concern in systems with limited resources.
It is not always the most efficient data structure. In some cases, other
data structures like heaps or binary search trees may be more efficient for
certain operations, such as finding the minimum or maximum element in
the queue.
At times it is less predictable:. This is because the order of elements
in a priority queue is determined by their priority values, the order in
which elements are retrieved may be less predictable than with other
data structures like stacks or queues, which follow a first-in, first-out
(FIFO) or last-in, first-out (LIFO) order.

You might also like