Download presentation
Presentation is loading. Please wait.
Published byAlaina Ayre Modified over 9 years ago
1
COMPSCI 105 SS 2015 Principles of Computer Science Queues
2
Agenda & Reading Agenda Introduction Queue Abstract Data Type (ADT) Implementing a queue using a list Using the Queue ADT to solve problems A Circular Queue The Deque Abstract Data Type Reading Textbook: Problem Solving with Algorithms and Data Structures Chapter 3 lecture 11COMPSCI1052
3
1 Introduction What is a Queue? Queues are appropriate for many real-world situations Example: A line to buy a movie ticket Computer applications, e.g. a request to print a document A queue is an ordered collection of items where the addition of new items happens at one end (the rear or back of the queue) and the removal of existing items always takes place at the other end (the front of the queue). New items enter at the back, or rear, of the queue Items leave from the front of the queue First-in, first-out (FIFO) property: The first item inserted into a queue is the first item to leave lecture 11COMPSCI1053
4
Queues implement the FIFO (first-in first-out) policy: e.g. the printer / job queue! enqueue( o ) is_empty() peek() dequeue() 1 Introduction More formally… front Rear of the queue lecture 11COMPSCI1054
5
1 Introduction ADT Queue Operations What are the operations which can be used with a Stack Abstract Data? Create an empty queue: Determine whether a queue is empty: Add a new item to the queue: enqueue Remove from the queue the item that was added earliest: dequeue Retrieve from the queue the item that was added earliest: peek lecture 11COMPSCI1055
6
2 The Queue ADT The Queue Abstract Data Type Queue() creates a new queue that is empty. It needs no parameters and returns an empty queue. enqueue(item) adds a new item to the rear of the queue. It needs the item and returns nothing. dequeue() removes the front item from the queue. It needs no parameters and returns the item. The queue is modified. is_empty() tests to see whether the queue is empty. It needs no parameters and returns a boolean value. size() returns the number of items in the queue. It needs no parameters and returns an integer. lecture 11COMPSCI1056
7
2 The Queue Implementation In Python We use a python List data structure to implement the queue. Remember: the addition of new items takes place at the beginning of the list the removal of existing items takes place at the end of the list class Queue: def __init__(self): self.items = [] def is_empty(self): return self.items == [] def size(self): return len(self.items) def enqueue(self, item): self.items.insert(0,item) def dequeue(self): return self.items.pop() class Queue: def __init__(self): self.items = [] def is_empty(self): return self.items == [] def size(self): return len(self.items) def enqueue(self, item): self.items.insert(0,item) def dequeue(self): return self.items.pop() Enqueue (rear of the queue) Dequeue (front of the queue) lecture 11COMPSCI1057
8
2 The Queue ADT Code Example – Result Queue operations, state of the queue, values returned q.is_empty() q.enqueue(4) q.enqueue('dog') q.enqueue(True) q.size() q.is_empty() q.enqueue(8.4) q.dequeue() q.size() [] [4] ['dog',4] [True,'dog',4] [8.4,True,'dog',4] [8.4,True,'dog'] [8.4,True] True 3 False 4 'dog' 2 q = Queue() Enqueue: (rear of the queue) (beginning of the list) lecture 11COMPSCI1058
9
3 Applications Example Applications Simulation: Hot Potato lecture 11COMPSCI1059
10
3 Applications 1. Simulation: Hot Potato Six person game of Hot Potato Children form a circle and pass an item from neighbour to neighbour as fast as they can. At a certain point in the game, the action is stopped and the child who has the item (the potato) is removed from the circle. Play continues until only one child is left. lecture 11COMPSCI10510
11
3 Applications 1. Simulation: Hot Potato Simulation of Hot Potato 1 st round: 2 nd round: 3 rd round: Finally hotPotato([Bill, David, Susan, Jane], 3) JaneSusanDavidBill JaneSusanDavid Enqueue (rear of the queue) dequeue DavidBillJaneSusan 0 1 2 DavidBillJane Remove Jane BillSusanDavid BillSusan 0 1 2 DavidBill Remove Bill DavidSusan David 0 1 2 Susan Remove Susan David lecture 11COMPSCI10511
12
3 Applications Hot Potato- Code def hotPotato(namelist, num): simqueue = Queue() for name in namelist: simqueue.enqueue(name) while simqueue.size() > 1: for i in range(num): simqueue.enqueue(simqueue.dequeue()) simqueue.dequeue() return simqueue.dequeue() def hotPotato(namelist, num): simqueue = Queue() for name in namelist: simqueue.enqueue(name) while simqueue.size() > 1: for i in range(num): simqueue.enqueue(simqueue.dequeue()) simqueue.dequeue() return simqueue.dequeue() Return the name when there is only ONE name remains in the queue Move element from the front of the queue to the end lecture 11COMPSCI10512
13
4 Circular Queue Circular Queue What is the Big-O performance of enqueue and dequeue of the implementation using Python List? enqueue(…): O(n) Shifting array elements to the right after each addition – too Expensive! dequeue() : O(1) Another Implementation: Circular Queue enqueue & dequeue : O(1) Items can be added/removed without shifting the other items in the process def enqueue(self, item): self.items.insert(0,item) def dequeue(self): return self.items.pop() def enqueue(self, item): self.items.insert(0,item) def dequeue(self): return self.items.pop() Viewed as a circle instead of line lecture 11COMPSCI10513
14
4 Circular Queue Set up Uses a Python list data structure to store the items in the queue. The list has an initial capacity (all elements None) Keeps an index of the current front of the queue and of the current back of the queue. set front to 0, set back to MAX_QUEUE – 1, set count to 0 New items are enqueued at the back index position Items are dequeued at the front index position. A count of the queue items to detect queue-full and queue- empty conditions To initialize the queue lecture 11COMPSCI10514
15
4 Circular Queue How To Advance Queue-empty: front is one slot ahead of back When either front or back advances past MAX_QUEUE - 1, it wraps around to 0 The wrap-around effect: by using Modulus (%) arithmetic operator enqueue If it is not full, dequeue If it is not empty self.back = (self.back + 1) % self.MAX_QUEUE self.items[self.back] = item self.count += 1 self.back = (self.back + 1) % self.MAX_QUEUE self.items[self.back] = item self.count += 1 item = self.items[self.front] self.front = (self.front + 1) % self.MAX_QUEUE self.count -= 1 return item item = self.items[self.front] self.front = (self.front + 1) % self.MAX_QUEUE self.count -= 1 return item lecture 11COMPSCI10515
16
4 Circular Queue enqueue(32) Before: After: New item is inserted at the position following back back is advanced by one position count is incremented by 1 self.back = (self.back + 1) % self.MAX_QUEUE self.items[self.back] = item self.count += 1 self.back = (self.back + 1) % self.MAX_QUEUE self.items[self.back] = item self.count += 1 enqueue lecture 11COMPSCI10516 5 7 5 7
17
4 Circular Queue dequeue() Before: After: Value in front position is removed and returned front is advanced by 1 count is decremented by 1 item = self.items[self.front] self.front = (self.front + 1) % self.MAX_QUEUE self.count -= 1 return item item = self.items[self.front] self.front = (self.front + 1) % self.MAX_QUEUE self.count -= 1 return item Two spaces left! dequeue lecture 11COMPSCI10517 5 7 5 7
18
4 Circular Queue enqueue(8) and enqueue(50) Before: After: After running the first enqueue, back = 6 After running the second enqueue, back = 0 as the “Back” is wrapped around the list Two spaces left! enqueue lecture 11COMPSCI10518 5 7 5 7
19
4 Circular Queue Empty ? Full? front and back cannot be used to distinguish between queue-full and queue-empty conditions for a circular array Case 1: q = Queuecircular(8) q.enqueue(5) q.enqueue(2) q.enqueue(1) q.enqueue(7) q.enqueue(9) q.dequeue() q = Queuecircular(8) q.enqueue(5) q.enqueue(2) q.enqueue(1) q.enqueue(7) q.enqueue(9) q.dequeue() 5 2 front = 5 back = 4 lecture 11COMPSCI10519
20
4 Circular Queue Empty ? Full? Case 2: is_empty() is_full()... q.enqueue(2) q.enqueue(4) q.enqueue(1) q.enqueue(7) q.enqueue(6) q.enqueue(3) q.enqueue(8)... q.enqueue(2) q.enqueue(4) q.enqueue(1) q.enqueue(7) q.enqueue(6) q.enqueue(3) q.enqueue(8) q.enqueue(9) front = 5 back = 4 (Same as before)! return self.count == 0 return self.MAX_QUEUE <= self.count lecture 11COMPSCI10520
21
5 Deque Deque Abstract Data Type Deque - Double Ended Queue A deque is an ordered collection of items where items are added and removed from either end, either front or back. The newest item is at one of the ends lecture 11COMPSCI10521
22
5 Deque ADT Deque Operations What are the operations which can be used with a Deque Abstract Data? Create an empty deque: Determine whether a deque is empty: Add a new item to the deque: add_front() add_rear() Remove from the deque the item that was added earliest: remove_front() remove_rear() lecture 11COMPSCI10522
23
5 Deque In Python We use a python List data structure to implement the deque. class Deque: def __init__(self): self.items = []... def add_front(self, item): self.items.append(item) def add_rear(self, item): self.items.insert(0,item) def remove_front(self): return self.items.pop() def remove_rear(self): return self.items.pop(0) class Deque: def __init__(self): self.items = []... def add_front(self, item): self.items.append(item) def add_rear(self, item): self.items.insert(0,item) def remove_front(self): return self.items.pop() def remove_rear(self): return self.items.pop(0) (rear of the deque) (front of the deque) lecture 11COMPSCI10523
24
5 Deque Code Example – Result Deque operations, state of the deque, values returned d = Deque() d.is_empty() d.add_rear(4) d.add_rear('dog') d.add_front('cat') d.add_front(True) d.size() d.is_empty() d.add_rear(8.4) d.remove_rear() d.remove_front() [] [4] ['dog',4,] ['dog',4,'cat'] ['dog',4,'cat',True] [8.4,'dog',4,'cat',True] ['dog',4,'cat',True] ['dog',4,'cat'] True 4 False 8.4 True (rear of the deque) (front of the deque) lecture 11COMPSCI10524
25
5 Deque Big-O Performance O(1) add_front() remove_front() O(n) add_rear() remove_rear() def add_front(self, item): self.items.append(item) def add_rear(self, item): self.items.insert(0,item) def remove_front(self): return self.items.pop() def remove_rear(self): return self.items.pop(0) def add_front(self, item): self.items.append(item) def add_rear(self, item): self.items.insert(0,item) def remove_front(self): return self.items.pop() def remove_rear(self): return self.items.pop(0) (rear of the deque) (front of the deque) lecture 11COMPSCI10525
26
A string which reads the same either left to right, or right to left is known as a palindrome radar deed A dog, a plan, a canal: pagoda. 5 Deque Application: Palindrome Checker lecture 11COMPSCI10526
27
Create a deque to store the characters of the string The front of the deque will hold the first character of the string and the rear of the deque will hold the last character Remove both of them directly, we can compare them and continue only if they match. If we can keep matching first and the last items, we will eventually either run out of characters or be left with a deque of size 1 In either case, the string must be a palindrome. 5 Deque Palindrome Checker - Algorithm lecture 11COMPSCI10527
28
Summary The definition of the queue operations gives the ADT queue first-in, first-out (FIFO) behaviour To distinguish between the queue-full and queue-empty conditions in a queue implementation that uses a circular array, count the number of items in the queue Models of real-world systems often use queues lecture 11COMPSCI10528
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.