The order in which the elements should be removed is decided by the priority of the element.
Rules to be followed to maintain a priority queue:
1. The element with a higher priority is processed before any element of lower priority.
2. If there were elements with the same priority, then the element added first in the queue would get processed first.
Priority queues are used for implementing job scheduling by the operating system where jobs with higher priority are to be processed first.
Another application of priority queues is in simulation systems where the priority corresponds to event times.
There are two ways to implement priority queues:
Method 1:
Using separate queues for each priority and following FIFO (First In First Out) behavior.
Jobs are always removed from the front of the queue. The elements in the second queue are removed only when the first queue is empty, and the elements from the third queue are removed only when the second queue is empty, and so on.
Method 2:
Priority queue is implemented by using a structure for a queue.
typedef struct
{
int Data;
int priority;
The highest priority element is at the front and that of the lowest priority is at the rear. When an element is to be deleted, it behaves as a normal queue, the element at front, which has the highest priority, is deleted first.
The two ways to implement a priority queue are sorted list and unsorted list.
Using sorted implementation deletion is easy (delete from beginning of list) but insertion is hard (find proper location of element). A linked list is convenient for this implementation.
0 comments:
Post a Comment