Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
148 views

Priority Queue (Data Structures) - Javatpoint

A priority queue is a data structure that orders elements based on their priority, with the highest priority element being removed first. It supports insertion and removal of elements in logarithmic time. The heap data structure is commonly used to implement priority queues efficiently, allowing insertion, removal, and access to the highest priority element all in O(log n) time. Priority queues have applications in algorithms like Dijkstra's shortest path and Prim's minimum spanning tree.

Uploaded by

Govinda Das
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
148 views

Priority Queue (Data Structures) - Javatpoint

A priority queue is a data structure that orders elements based on their priority, with the highest priority element being removed first. It supports insertion and removal of elements in logarithmic time. The heap data structure is commonly used to implement priority queues efficiently, allowing insertion, removal, and access to the highest priority element all in O(log n) time. Priority queues have applications in algorithms like Dijkstra's shortest path and Prim's minimum spanning tree.

Uploaded by

Govinda Das
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

What is a priority queue?

A priority queue is an abstract data type that behaves similarly to the normal queue except that
each element has some priority, i.e., the element with the highest priority would come first in a
priority queue. The priority of the elements in a priority queue will determine the order in which
elements are removed from the priority queue.

The priority queue supports only comparable elements, which means that the elements are either
arranged in an ascending or descending order.

For example, suppose we have some values like 1, 3, 4, 8, 14, 22 inserted in a priority queue with an
ordering imposed on the values is from least to the greatest. Therefore, the 1 number would be
having the highest priority while 22 will be having the lowest priority.

Characteristics of a Priority queue

A priority queue is an extension of a queue that contains the following characteristics:

Every element in a priority queue has some priority associated with it.

An element with the higher priority will be deleted before the deletion of the lesser priority.

If two elements in a priority queue have the same priority, they will be arranged using the
FIFO principle.

Let's understand the priority queue through an example.

We have a priority queue that contains the following values:

1, 3, 4, 8, 14, 22

All the values are arranged in ascending order. Now, we will observe how the priority queue will
look after performing the following operations:

poll(): This function will remove the highest priority element from the priority queue. In the
above priority queue, the '1' element has the highest priority, so it will be removed from the
priority queue.

add(2): This function will insert '2' element in a priority queue. As 2 is the smallest element
among all the numbers so it will obtain the highest priority.

poll(): It will remove '2' element from the priority queue as it has the highest priority queue.

add(5): It will insert 5 element after 4 as 5 is larger than 4 and lesser than 8, so it will obtain
the third highest priority in a priority queue.
AD

Types of Priority Queue

There are two types of priority queue:

Ascending order priority queue: In ascending order priority queue, a lower priority number
is given as a higher priority in a priority. For example, we take the numbers from 1 to 5
arranged in an ascending order like 1,2,3,4,5; therefore, the smallest number, i.e., 1 is given as
the highest priority in a priority queue.

Descending order priority queue: In descending order priority queue, a higher priority
number is given as a higher priority in a priority. For example, we take the numbers from 1 to
5 arranged in descending order like 5, 4, 3, 2, 1; therefore, the largest number, i.e., 5 is given
as the highest priority in a priority queue.
Representation of priority queue

Now, we will see how to represent the priority queue through a one-way list.

We will create the priority queue by using the list given below in which INFO list contains the data
elements, PRN list contains the priority numbers of each data element available in the INFO list, and
LINK basically contains the address of the next node.

Let's create the priority queue step by step.

In the case of priority queue, lower priority number is considered the higher priority, i.e.,
lower priority number = higher priority.

Step 1: In the list, lower priority number is 1, whose data value is 333, so it will be inserted in the list
as shown in the below diagram:

Step 2: After inserting 333, priority number 2 is having a higher priority, and data values associated
with this priority are 222 and 111. So, this data will be inserted based on the FIFO principle;
therefore 222 will be added first and then 111.

Step 3: After inserting the elements of priority 2, the next higher priority number is 4 and data
elements associated with 4 priority numbers are 444, 555, 777. In this case, elements would be
inserted based on the FIFO principle; therefore, 444 will be added first, then 555, and then 777.

Step 4: After inserting the elements of priority 4, the next higher priority number is 5, and the value
associated with priority 5 is 666, so it will be inserted at the end of the queue.
AD
Implementation of Priority Queue

The priority queue can be implemented in four ways that include arrays, linked list, heap data
structure and binary search tree. The heap data structure is the most efficient way of implementing
the priority queue, so we will implement the priority queue using a heap data structure in this topic.
Now, first we understand the reason why heap is the most efficient way among all the other data
structures.

Analysis of complexities using different implementations

Implementation add Remove peek

Linked list O(1) O(n) O(n)

Binary heap O(logn) O(logn) O(1)

Binary search tree O(logn) O(logn) O(1)

What is Heap?

A heap is a tree-based data structure that forms a complete binary tree, and satisfies the heap
property. If A is a parent node of B, then A is ordered with respect to the node B for all nodes A and
B in a heap. It means that the value of the parent node could be more than or equal to the value of
the child node, or the value of the parent node could be less than or equal to the value of the child
node. Therefore, we can say that there are two types of heaps:

Max heap: The max heap is a heap in which the value of the parent node is greater than the
value of the child nodes.
Min heap: The min heap is a heap in which the value of the parent node is less than the
value of the child nodes.

Both the heaps are the binary heap, as each has exactly two child nodes.

Priority Queue Operations

The common operations that we can perform on a priority queue are insertion, deletion and peek.
Let's see how we can maintain the heap data structure.
AD
Inserting the element in a priority queue (max heap)

If we insert an element in a priority queue, it will move to the empty slot by looking from top to
bottom and left to right.

If the element is not in a correct place then it is compared with the parent node; if it is found out of
order, elements are swapped. This process continues until the element is placed in a correct
position.

Removing the minimum element from the priority queue

As we know that in a max heap, the maximum element is the root node. When we remove the root
node, it creates an empty slot. The last inserted element will be added in this empty slot. Then, this
element is compared with the child nodes, i.e., left-child and right child, and swap with the smaller
of the two. It keeps moving down the tree until the heap property is restored.
Applications of Priority queue

The following are the applications of the priority queue:

It is used in the Dijkstra's shortest path algorithm.

It is used in prim's algorithm

It is used in data compression techniques like Huffman code.

It is used in heap sort.

It is also used in operating system like priority scheduling, load balancing and interrupt
handling.

Program to create the priority queue using the binary max heap.

#include <stdio.h>  
#include <stdio.h>  
int heap[40];  
int size=-1;  
  
// retrieving the parent node of the child node  
int parent(int i)   
{   
    
    return (i - 1) / 2;   
}   
  
// retrieving the left child of the parent node.  
int left_child(int i)  
{  
 return i+1;   
}  
// retrieving the right child of the parent  
int right_child(int i)  
{  
 return i+2;   
}  
// Returning the element having the highest priority  
int get_Max()  
{  
    return heap[0];  
}  
//Returning the element having the minimum priority  
int get_Min()  
{  
    return heap[size];  
}  
// function to move the node up the tree in order to restore the heap property.  
void moveUp(int i)   
{   
    while (i > 0)   
    {  
        // swapping parent node with a child node  
        if(heap[parent(i)] < heap[i]) {   
    
        int temp;  
        temp=heap[parent(i)];  
        heap[parent(i)]=heap[i];  
        heap[i]=temp;  
          
          
    }   
       // updating the value of i to i/2   
       i=i/2;  
    }  
}   
  
//function to move the node down the tree in order to restore the heap property.  
void moveDown(int k)  
{  
    int index = k;   
    
    // getting the location of the Left Child   
    int left = left_child(k);   
    
    if (left <= size && heap[left] > heap[index]) {   
        index = left;   
    }   
    
    // getting the location of the Right Child   
    int right = right_child(k);   
    
    if (right <= size && heap[right] > heap[index]) {   
        index = right;   
    }   
    
    // If k is not equal to index   
    if (k != index) {   
      int temp;  
      temp=heap[index];  
      heap[index]=heap[k];  
      heap[k]=temp;  
        moveDown(index);   
    }   
}  
  
// Removing the element of maximum priority  
void removeMax()  
{  
    int r= heap[0];  
    heap[0]=heap[size];  
    size=size-1;  
    moveDown(0);  
}  
//inserting the element in a priority queue  
void insert(int p)   
{   
    size = size + 1;   
    heap[size] = p;   
    
    // move Up to maintain heap property   
    moveUp(size);   
}   
  
//Removing the element from the priority queue at a given index i.  
void delete(int i)   
{   
    heap[i] = heap[0] + 1;   
    
   // move the node stored at ith location is shifted to the root node  
    moveUp(i);   
    
    // Removing the node having maximum priority   
    removeMax();   
}   
int main()  
{  
    // Inserting the elements in a priority queue  
  
    insert(20);  
    insert(19);  
    insert(21);  
    insert(18);  
    insert(12);  
    insert(17);  
    insert(15);  
    insert(16);  
    insert(14);  
    int i=0;  
  
 printf("Elements in a priority queue are : ");  
 for(int i=0;i<=size;i++)  
    {  
       printf("%d ",heap[i]);  
    }  
    delete(2); // deleting the element whose index is 2.  
    printf("\nElements in a priority queue after deleting the element are : ");  
    for(int i=0;i<=size;i++)  
    {  
       printf("%d ",heap[i]);  
    }  
int max=get_Max();  
    printf("\nThe element which is having the highest priority is %d: ",max);  
     
  
    int min=get_Min();  
        printf("\nThe element which is having the minimum priority is : %d",min);  
    return 0;  
}  

In the above program, we have created the following functions:

int parent(int i): This function returns the index of the parent node of a child node, i.e., i.

int left_child(int i): This function returns the index of the left child of a given index, i.e., i.

int right_child(int i): This function returns the index of the right child of a given index, i.e., i.

void moveUp(int i): This function will keep moving the node up the tree until the heap
property is restored.

void moveDown(int i): This function will keep moving the node down the tree until the heap
property is restored.

void removeMax(): This function removes the element which is having the highest priority.

void insert(int p): It inserts the element in a priority queue which is passed as an argument
in a function.

void delete(int i): It deletes the element from a priority queue at a given index.

int get_Max(): It returns the element which is having the highest priority, and we know that
in max heap, the root node contains the element which has the largest value, and highest
priority.

int get_Min(): It returns the element which is having the minimum priority, and we know that
in max heap, the last node contains the element which has the smallest value, and lowest
priority.

Output

You might also like