240 likes | 312 Views
Computer Science 112. Fundamentals of Programming II Queues and Priority Queues. Queues: Formal Properties. A queue is a linear collection that supports first-in, first-out (FIFO) access Insertions occur at one end, called the rear Removals occur at the other end, called the front. D.
E N D
Computer Science 112 Fundamentals of Programming II Queues and Priority Queues
Queues: Formal Properties • A queue is a linear collection that supports first-in, first-out (FIFO) access • Insertions occur at one end, called the rear • Removals occur at the other end, called the front
D D D D D D D D D D FIFO Access Front of queue remove add Rear of queue
Minimal Set of Queue Operations q.isEmpty() Returns True if empty, False otherwise len(q) Returns the number of items in the queue str(q) Returns a string representation iter(q) Supports a for loop item in q True if item is in queue, False otherwise q1 + q2 Returns a new queue with items in q1 and q2 q1 == q2 Equality test for two queues
Minimal Set of Queue Operations q.isEmpty() Returns True if empty, False otherwise len(q) Returns the number of items in the queue str(q) Returns a string representation iter(q) Supports a for loop item in q True if item is in queue, False otherwise q1 + q2 Returns a new queue with items in q1 and q2 q1 == q2 Equality test for two queues q.add(item) Adds item to the rear of the queue q.pop() Removes and returns front item q.peek() Returns item at the front of the queue The precondition of pop and peek is that the queue is not empty.
Queue Implementations • Array-based • Linked (singly, with an extra tail pointer: the head is the front and the tail is the rear)
AbstractCollection object LinkedQueue ArrayQueue AbstractQueue A Realistic Queue Implementation
Example Use of a Queue queue = LinkedQueue([45, 66, 99]) while not queue.isEmpty()): print(queue.pop())
The Linked Implementation from node import Node fromabstractqueueimportAbstractQueue classLinkedQueue(AbstractQueue): def__init__(self, sourceCollection = None) self._front = self._rear = None AbstractQueue.__init__(self, sourceCollection) front rear 5 4 3 2
The Linked Implementation from node import Node fromabstractqueueimportAbstractQueue classLinkedQueue(AbstractQueue): def__init__(self, sourceCollection = None): self._front = self._rear = None AbstractQueue.__init__(self, sourceCollection) defadd(self, item): newNode = Node(item) ifself.isEmpty(): self._front = newNode else: self._rear.next = newNode self._rear = newNode
Queue Applications Queues are useful for algorithms that serve clients on a first-come first-served basis • Process scheduling in operating systems • Modeling and simulation of real-world processes, such as supermarket checkout situations
Priority Queues • Similar to a queue, except that items can grouped by priority for earlier service • Elements are maintained in sorted order, with the smallest ones having the highest priority • When two elements have the same priority, they are served in FIFO order
Priority Queue ADT: Implementations • Commonly implemented with a heap (will discuss in several weeks) • A linked priority queue is a type of linked queue that imposes a priority ordering on its elements • Can inherit the data and most of the behavior of a linked queue
AbstractCollection object LinkedQueue ArrayQueue AbstractQueue All operations except add are the same as in LinkedQueue The element type must be comparable LinkedPriorityQueue Place in the Queue Hierarchy
LinkedPriorityQueue • Extends LinkedQueue • Overrides the add method • Otherwise, the behavior is the same!
Strategy for add • If queue is empty or the new item >= the rear item, call LinkedQueue.add • Otherwise, use a probe and trailer to search for the first item > the new item • Insert the new item before that item
LinkedPriorityQueue from node import Node fromlinkedqueueimportLinkedQueue classLinkedPriorityQueue(LinkedQueue): def__init__(self, sourceCollection = None): LinkedQueue.__init__(self, sourceCollection) defadd(self, item): if queue is empty or item >= the last one LinkedQueue.add(self, item) elifitem < the first one insert at head else: initialize a probe and a trailer while item >= data advance trailer and probe newNode = Node(item, probe) insert between probe and trailer
+ and __add__ >> q1 = LinkedQueue([2, 4, 6]) >> q2 = LinkedQueue([1, 3, 5]) >> print(q1 + q2) [2, 4, 6, 1, 3, 5] + maintains FIFO order for plain queues Uses __add__ method in AbstractCollection
+ and __add__ >> q1 = LinkedPriorityQueue([2, 4, 6]) >> q2 = LinkedPriorityQueue([1, 3, 5]) >> print(q1 + q2) [1, 2, 3, 4, 5, 6] + maintains sorted order for priority queues Uses __add__ method in AbstractCollection
The Comparable Wrapper Class • Provides an easy way to tag existing objects with priority values, if those objects are not already comparable • Or can override the existing ordering of comparable objects, if needed • Provides the conventional interface for the comparison operators and str
Using Comparable pq = LinkedPriorityQueue() pq.add("Ken") pq.add("Sam") pq.add("Ann") for item inpq: print(item)
Using Comparable pq = LinkedPriorityQueue() pq.add("Ken") pq.add("Sam") pq.add("Ann") for item inpq: print(item) pq = LinkedPriorityQueue() pq.add(Comparable("Ken", 2)) pq.add(Comparable("Sam", 1)) pq.add(Comparable("Ann", 2)) for item inpq: print(item)
Defining Comparable classComparable(object): def__init__(self, data, priority = 1): self.data = data self.priority = priority def__str__(self): returnstr(self.data) def__eq__(self, other): if self is other: return True iftype(self) != type(other): return False returnself.priority == other.priority def__lt__(self, other): returnself.priority < other.priority def__le__(self, other): returnself.priority <= other.priority
For Monday (after break) Array-Based Queues