Computer Science 112 Fundamentals of Programming II Queues and Priority Queues.

Slides:



Advertisements
Similar presentations
Stacks, Queues, and Linked Lists
Advertisements

Computer Science 112 Fundamentals of Programming II List Iterators.
Computer Science 112 Fundamentals of Programming II Overview of Collections.
Computer Science 112 Fundamentals of Programming II Array-Based Queues.
Queues CS-212 Dick Steflik. Queues First In, First Out operation – FIFO As items are added they are chronologically ordered, items are removed in their.
CHAPTER 7 Queues.
ADT Queue 1. What is a Queue? 2. STL Queue 3. Array Implementation of Queue 4. Linked List Implementation of Queue 5. Priority Queue.
Fundamentals of Python: From First Programs Through Data Structures
CSC 212 – Data Structures. Using Stack Stack Limitations  Great for Pez dispensers, JVMs,& methods  All of these use most recent item added only 
COMP 103 Linked Stack and Linked Queue.
Computer Science 112 Fundamentals of Programming II Lists.
Fundamentals of Programming II Inheritance and Abstract Classes
Queues Chapter 6. Chapter Objectives  To learn how to represent a waiting line (queue) and how to use the methods in the Queue interface for insertion.
CS 106 Introduction to Computer Science I 12 / 06 / 2006 Instructor: Michael Eckmann.
ITEC200 Week06 Queues. 2 Learning Objectives – Week06 Queues (Ch6) Students can Manage data using the queue Abstract Data Type.
COMPSCI 105 S Principles of Computer Science Linked Lists 2.
Unit 11 1 Unit 11: Data Structures H We explore some simple techniques for organizing and managing information H This unit focuses on: Abstract Data Types.
Main Index Contents 11 Main Index Contents Model for a Queue Model for a Queue The Queue The Queue ADTQueue ADT (3 slides) Queue ADT Radix Sort Radix Sort.
Stacks, Queues & Deques CSC212.
Queues Chapter 6. Chapter 6: Queues2 Chapter Objectives To learn how to represent a waiting line (queue) and how to use the methods in the Queue interface.
Fundamentals of Python: From First Programs Through Data Structures
Queues CS-240 & CS-341 Dick Steflik. Queues First In, First Out operation – FIFO As items are added they are chronologically ordered, items are removed.
1 Stack Data : a collection of homogeneous elements arranged in a sequence. Only the first element may be accessed Main Operations: Push : insert an element.
1 Hash Tables  a hash table is an array of size Tsize  has index positions 0.. Tsize-1  two types of hash tables  open hash table  array element type.
COMP 121 Week 14: Queues. Objectives Learn how to represent a queue Learn how to use the methods in the Queue interface Understand how to implement the.
Review 1 Introduction Representation of Linear Array In Memory Operations on linear Arrays Traverse Insert Delete Example.
© 2006 Pearson Addison-Wesley. All rights reserved8 A-1 Chapter 8 Queues (slightly modified by Dan Fleck)
CM0551 Exam Prep. What are an algorithm’s time and space complexity? (2 marks) Answer: The growth rate of the algorithm’s time requirement and the computer.
Computer Science 112 Fundamentals of Programming II Introduction to Stacks.
October 18, Algorithms and Data Structures Lecture V Simonas Šaltenis Nykredit Center for Database Research Aalborg University
COMP 103 Linked Lists. 2 RECAP-TODAY RECAP  Linked Structures: LinkedNode  Iterating and printing Linked Nodes  Inserting and removing Linked Nodes.
LECTURE 26: QUEUES CSC 212 – Data Structures. Using Stack.
Lecture7: Queue Bohyung Han CSE, POSTECH CSED233: Data Structures (2014F)
Computer Science 112 Fundamentals of Programming II Interfaces and Implementations.
Computer Science 112 Fundamentals of Programming II Binary Search Trees.
Chapter 8 Queue I CS Data Structures I COSC2006 April 24, 2017
Computer Science 112 Fundamentals of Programming II Implementation Strategies for Unordered Collections.
Data Structures Chapter 6. Data Structure A data structure is a representation of data and the operations allowed on that data. Examples: 1.Array 2.Record.
Computer Science Department Data Structures and Algorithms Queues Lecture 5.
Queues. Like Stacks, Queues are a special type of List for storing collections of entities. Stacks are Lists where insertions (pushes) and deletions (pops)
1 Stacks & Queues CSC Stacks & Queues Stack: Last In First Out (LIFO). –Used in procedure calls, to compute arithmetic expressions etc. Queue: First.
Chapter 8 Queues. © 2004 Pearson Addison-Wesley. All rights reserved 8-2 The Abstract Data Type Queue A queue –New items enter at the back, or rear, of.
Question of the Day  How can you change the position of 1 toothpick and leave the giraffe in exactly the same form, but possibly mirror-imaged or oriented.
Give Eg:? Queues. Introduction DEFINITION: A Queue is an ordered collection of element in which insertions are made at one end and deletions are made.
Computer Science 112 Fundamentals of Programming II Iterators.
Data Structures Intro2CS – week Stack ADT (Abstract Data Type) A container with 3 basic actions: – push(item) – pop() – is_empty() Semantics: –
Unit 2 - Stack and Queue Slides 18 to end. Queue CMPT Anne Lavergne18.
Fundamentals of Programming II Linked Lists
Review Array Array Elements Accessing array elements
The List ADT.
Data Structure By Amee Trivedi.
Queues Chapter 4.
Fundamentals of Programming II Overview of Collections
CC 215 Data Structures Queue ADT
Fundamentals of Programming II Binary Search Trees
Queues Queues Queues.
Queues Chapter 4.
Priority Queue.
Chapter 13 Queues and Priority Queues
structures and their relationships." - Linus Torvalds
Queues.
Queues: Implemented using Arrays
Programming Abstractions
Stack A data structure in which elements are inserted and removed only at one end (called the top). Enforces Last-In-First-Out (LIFO) Uses of Stacks Evaluating.
Queues CSC212.
Queues: Implemented using Linked Lists
structures and their relationships." - Linus Torvalds
Queues.
CMPT 225 Lecture 8 – Queue.
Data Structures & Programming
Presentation transcript:

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

FIFO Access D D D D DDD add D D D remove Rear of queue Front of queue

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 qTrue if item is in queue, False otherwise q1 + q2Returns a new queue with items in q1 and q2 q1 == q2Equality 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 qTrue if item is in queue, False otherwise q1 + q2Returns a new queue with items in q1 and q2 q1 == q2Equality 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. Minimal Set of Queue Operations

Queue Implementations Array-based Linked (singly, with an extra tail pointer: the head is the front and the tail is the rear)

A Realistic Queue Implementation AbstractCollectionobject AbstractQueue ArrayQueueLinkedQueue

queue = LinkedQueue([45, 66, 99]) while not queue.isEmpty()): print(queue.pop()) Example Use of a Queue

from node import Node from abstractqueue import AbstractQueue class LinkedQueue(AbstractQueue): def __init__(self, sourceCollection = None) self._front = self._rear = None AbstractQueue.__init__(self, sourceCollection) The Linked Implementation 5432 front rear

from node import Node from abstractqueue import AbstractQueue class LinkedQueue(AbstractQueue): def __init__(self, sourceCollection = None): self._front = self._rear = None AbstractQueue.__init__(self, sourceCollection) def add(self, item): newNode = Node(item) if self.isEmpty(): self._front = newNode else: self._rear.next = newNode self._rear = newNode self._size += 1 The Linked Implementation

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

Place in the Queue Hierarchy LinkedPriorityQueue All operations except add are the same as in LinkedQueue The element type must be comparable AbstractCollectionobject AbstractQueue ArrayQueueLinkedQueue

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 from linkedqueue import LinkedQueue class LinkedPriorityQueue(LinkedQueue): def __init__(self, sourceCollection = None): LinkedQueue.__init__(self, sourceCollection) def add(self, item): if self.isEmpty() or item >= the last one LinkedQueue.add(self, item) elif item < 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 in pq: print(item)

Using Comparable pq = LinkedPriorityQueue() pq.add(Comparable("Ken", 2)) pq.add(Comparable("Sam", 1)) pq.add(Comparable("Ann", 2)) for item in pq: print(item) pq = LinkedPriorityQueue() pq.add("Ken") pq.add("Sam") pq.add("Ann") for item in pq: print(item)

Defining Comparable class Comparable(object): def __init__(self, data, priority = 1): self.data = data self.priority = priority def __str__(self): return str(self.data) def __eq__(self, other): if self is other: return True if type(self) != type(other): return False return self.priority == other.priority def __lt__(self, other): return self.priority < other.priority def __le__(self, other): return self.priority <= other.priority

For Monday (after break) Array-Based Queues