Priority Queue in Python
Priority Queues are abstract data structures where each data/value in the queue has a certain priority. For example, In airlines, baggage with the title “Business” or “First-class” arrives earlier than the rest.
Priority Queue is an extension of the queue with the following properties.
- 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.
Various applications of Priority queue in Computer Science are:
Job Scheduling algorithms, CPU and Disk Scheduling, managing resources that are shared among different processes, etc.
Key differences between Priority Queue and Queue:
- In Queue, the oldest element is dequeued first. While, in Priority Queue, element based on highest priority is dequeued.
- When elements are popped out of a priority queue then result obtained in either sorted in Increasing order or in Decreasing Order. While, when elements are popped from a simple queue, a FIFO order of data is obtained in the result.
Below is simple implementation of priority queue.
12 1 14 7 14 12 7 1
Note that the time complexity of delete is O(n) in the above code. A better implementation is to use Binary Heap which is typically used to implement priority queue. Note that Python provides heapq in library also.
By using heap datastructure to implement Priority Queues, Time complexity: Insert Operation: O(log(n)) Delete Operation: O(log(n))