Chapter 5 Queues.

Slides:



Advertisements
Similar presentations
Queues A waiting line that grows by adding elements to its end and shrinks by taking elements from its front Line at the grocery store Cars in traffic.
Advertisements

Stacks, Queues, and Deques. 2 A stack is a last in, first out (LIFO) data structure Items are removed from a stack in the reverse order from the way they.
1 Queues (Continued) Applications for a queue Linked queue implementation Array queue implementation Circular array queue implementation Reading L&C 3.
queues1 Queues Data structures that wait their turn.
Topic 9 The Queue ADT.
CHAPTER 7 Queues.
5/4/20151 Queues Implementations. 5/4/20152 Outline Queues Basic operations Examples of useImplementations Array-based and linked list-based.
Queues 4/14/2017 5:24 PM 5.2 Queues Queues Dr Zeinab Eid.
Chapter 7 Queues. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Examine queue processing Define a queue abstract.
1 Queues (5.2) CSE 2011 Winter May Announcements York Programming Contest Link also available from.
Queues Ellen Walker CPSC 201 Data Structures Hiram College.
Chapter 5 Queues Modified. Chapter Scope Queue processing Comparing queue implementations 5 - 2Java Software Structures, 4th Edition, Lewis/Chase.
Chapter 14 Queues. Chapter Scope Queue processing Using queues to solve problems Various queue implementations Comparing queue implementations Java Foundations,
1 Queues Queue Concept Queue Design Considerations Queues in Java Collections APIs Queue Applications Reading L&C , 9.3.
CHAPTER 6 Stacks Array Implementation. 2 Stacks A stack is a linear collection whose elements are added and removed from one end The last element to be.
Fall 2007CS 2251 Queues Chapter 6. Fall 2007CS 2252 Chapter Objectives To learn how to represent a waiting line (queue) and how to use the methods in.
Stacks, Queues, and Deques
Chapter 14 Queues. First a Review Queue processing Using queues to solve problems – Optimizing customer service simulation – Ceasar ciphers – Palindrome.
Chapter 4 Linked Structures – Stacks Modified. Chapter Scope Object references as links Linked vs. array-based structures Managing linked lists Linked.
CSE 373 Data Structures and Algorithms Lecture 2: Queues.
Chapter 12 Introduction to Collections - Stacks
Chapter 7 Queues. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. 7-2 Chapter Objectives Examine queue processing Define a queue abstract.
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.
Chapter 3 Introduction to Collections – Stacks Modified
TK1924 Program Design & Problem Solving Session 2011/2012 L6: Queues.
Chapter 8 Lists. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Examine list processing and various ordering techniques.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 18: Stacks and Queues (part 3)
COS 312 DAY 20 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment 6 Posted – Due April 16 – Questions? Queues.
Data Structures Using Java1 Chapter 7 Queues. Data Structures Using Java2 Chapter Objectives Learn about queues Examine various queue operations Learn.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 5: Queues Java Software Structures: Designing and Using Data.
1 Stacks (Continued) and Queues Array Stack Implementation Linked Stack Implementation The java.util.Stack class Queue Abstract Data Type (ADT) Queue ADT.
CSE 373: Data Structures and Algorithms Lecture 2: Queues.
M180: Data Structures & Algorithms in Java Queues Arab Open University 1.
Copyright © Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by Tony.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 15: Sets and Maps Java Software Structures: Designing and Using.
1 Queues (Continued) Queue ADT Linked queue implementation Array queue implementation Circular array queue implementation Deque Reading L&C , 9.3.
Chapter 5 The Queue ADT. 5.1 Queues Queue A structure in which elements are added to the rear and removed from the front; a “first in, first out” (FIFO)
Collections & Stacks Collections A collection is an object that holds and organizes other objects It provides operations for accessing and managing.
Linked Structures - Stacks. Linked Structures An alternative to array-based implementations are linked structures A linked structure uses object references.
Collections (Stack, queue, tree, graph). References as Links References can be used to create a variety of linked structures, such as a linked list.
The Queue ADT.
CHAPTER 4: Linked Structures
Review Array Array Elements Accessing array elements
Queues 5/11/2018 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M. H.
Using Queues: Coded Messages
Queues Rem Collier Room A1.02
Queues Implementations 6/17/2018.
COS 312 DAY 21 Tony Gauvin.
CSE 373: Data Structures and Algorithms
Queues Queue Concept Queue Design Considerations
Queue.
Stacks and Queues.
Queues Queues Queues.
The Stack ADT. 3-2 Objectives Define a stack collection Use a stack to solve a problem Examine an array implementation of a stack.
Top Ten Words that Almost Rhyme with “Peas”
Chapter 4 Linked Structures - Stacks
Java Software Structures: John Lewis & Joseph Chase
THURSDAY, OCTOBER 17 IN LAB
Queues.
Stacks and Queues.
Chapter 4 Linked Structures - Stacks
Queues 11/22/2018 6:47 AM 5.2 Queues Queues Dr Zeinab Eid.
Cs212: Data Structures Computer Science Department Lecture 7: Queues.
CS210- Lecture 5 Jun 9, 2005 Agenda Queues
Copyright © Aiman Hanna All rights reserved
More Data Structures (Part 1)
Stacks, Queues, and Deques
Stacks and Queues.
CHAPTER 3: Collections—Stacks
Presentation transcript:

Chapter 5 Queues

Chapter Scope Queue processing Using queues to solve problems Various queue implementations Comparing queue implementations Java Software Structures, 4th Edition, Lewis/Chase

Queues A queue is a collection whose elements are added on one end and removed from the other Therefore a queue is managed in a FIFO fashion: first in, first out Elements are removed in the same order they arrive Any waiting line is a queue: the check out line at a grocery store the cars at a stop light an assembly line Java Software Structures, 4th Edition, Lewis/Chase

Queues A queue, conceptually: front rear element added at the rear end first in first out front rear Java Software Structures, 4th Edition, Lewis/Chase

Queues Standard queue operations: Java Software Structures, 4th Edition, Lewis/Chase

Queues in the Java API The Java Collections API is not consistent about its implementation of collections For queues, the API provides a Queue interface, then various classes such as LinkedList implement the interface Furthermore, the Queue interface defines two versions of the methods that add and remove elements from the queue The difference in the two versions is how exceptional situations are handled (next slide) Java Software Structures, 4th Edition, Lewis/Chase

Queues in the Java API boolean add(E e) Inserts the specified element into this queue Returns true upon success and throws an IllegalStateException if no space is available. boolean offer(E e) Inserts the specified element into this queue Returns true upon success and false if the insertion fails E element() Retrieves (does not remove) the head of this queue. Throws an exception if the queue is empty E peek() Retrieves (does not remove) the head of this queue Returns null if this queue is empty. E remove() Retrieves and removes the head of this queue. E poll() Retrieves and removes the head of this queue, or Java Software Structures, 4th Edition, Lewis/Chase

Coded Messages Let's use a queue to help us encode and decode messages A Ceasar cipher encodes a message by shifting each letter in a message by a constant amount k If k is 5, A becomes F, B becomes G, etc. However, this is fairly easy to break An improvement can be made by changing how much a letter is shifted depending on where the letter is in the message Java Software Structures, 4th Edition, Lewis/Chase

Coded Messages A repeating key is a series of integers that determine how much each character is shifted For example, consider the repeating key 3 1 7 4 2 5 To encode the first character in the message is shifted 3 positions to the right, the next 1, the next 7, and so on When the key is exhausted, we just start over at the beginning of the key 1 2 3 4 5 6 Java Software Structures, 4th Edition, Lewis/Chase

Coded Messages Decoding a message using a repeating key: a b c d e f g h I j k l m n o p q r s t u v w x y z 3 7 This example does not encode the space character. Java Software Structures, 4th Edition, Lewis/Chase

Java Software Structures, 4th Edition, Lewis/Chase /** * Codes demonstrates the use of queues to encrypt and decrypt messages. * * @author Lewis and Chase * @version 4.0 */ public class Codes { * Encode and decode a message using a key of values stored in * a queue. public static void main(String[] args) int[] key = {5, 12, -3, 8, -9, 4, 10}; Integer keyValue; String encoded = "", decoded = ""; String message = "All programmers are playwrights and all " + "computers are lousy actors."; Queue<Integer> encodingQueue = new LinkedList<Integer>(); // Queue: an interface Queue<Integer> decodingQueue = new LinkedList<Integer>(); // LinkedList: a class // load key queues for (int scan = 0; scan < key.length; scan++) encodingQueue.add(key[scan]); // 5, 12, -3, 8, -9, 4, 10 added to the queue decodingQueue.add(key[scan]); // Same } Java Software Structures, 4th Edition, Lewis/Chase

Java Software Structures, 4th Edition, Lewis/Chase // encode message for (int scan = 0; scan < message.length(); scan++) { keyValue = encodingQueue.remove(); encoded += (char) (message.charAt(scan) + keyValue); encodingQueue.add(keyValue); } System.out.println ("Encoded Message:\n" + encoded + "\n"); // decode message for (int scan = 0; scan < encoded.length(); scan++) keyValue = decodingQueue.remove(); decoded += (char) (encoded.charAt(scan) - keyValue); decodingQueue.add(keyValue); System.out.println ("Decoded Message:\n" + decoded); Java Software Structures, 4th Edition, Lewis/Chase

Coded Messages Java Software Structures, 4th Edition, Lewis/Chase

Coded Messages Summary of Queue Methods in Java Throws exception Returns special value Insert add(e) offer(e) Remove remove() poll() Examine element() peek() https://docs.oracle.com/javase/8/docs/api/java/util/Queue.html Java Software Structures, 4th Edition, Lewis/Chase

Ticket Counter Simulation Now let's use a queue to simulate the waiting line at a movie theatre The goal is to determine how many cashiers are needed to keep the wait time below 7 minutes We'll assume: customers arrive on average every 15 seconds processing a request takes two minutes (120 seconds) once a customer reaches a cashier Java Software Structures, 4th Edition, Lewis/Chase

Java Software Structures, 4th Edition, Lewis/Chase /** * Customer represents a waiting customer. * * @author Lewis and Chase * @version 4.0 */ public class Customer { private int arrivalTime, departureTime; * Creates a new customer with the specified arrival time. * @param arrives the arrival time public Customer(int arrives) arrivalTime = arrives; departureTime = 0; } * Returns the arrival time of this customer. * @return the arrival time public int getArrivalTime() return arrivalTime; Java Software Structures, 4th Edition, Lewis/Chase

Java Software Structures, 4th Edition, Lewis/Chase /** * Sets the departure time for this customer. * @param departs the departure time **/ public void setDepartureTime(int departs) { departureTime = departs; } * Returns the departure time of this customer. * @return the departure time */ public int getDepartureTime() return departureTime; * Computes and returns the total time spent by this customer. * @return the total customer time public int totalTime() // Turnaround time = Departure time – Arrival time { // = Service time + Wait time return departureTime - arrivalTime; Java Software Structures, 4th Edition, Lewis/Chase

Java Software Structures, 4th Edition, Lewis/Chase import java.util.*; /** * TicketCounter demonstrates the use of a queue for simulating a line of customers. * * @author Lewis and Chase * @version 4.0 */ public class TicketCounter { private final static int PROCESS_TIME = 120; private final static int MAX_CASHIERS = 10; private final static int NUM_CUSTOMERS = 100; public static void main(String[] args) Customer customer; Queue<Customer> customerQueue = new LinkedList<Customer>(); int[] cashierTime = new int[MAX_CASHIERS]; int totalTime, averageTime, departs, start; // run the simulation for various number of cashiers for (int cashiers = 0; cashiers < MAX_CASHIERS; cashiers++) // set each cashiers time to zero initially for (int count = 0; count < cashiers; count++) cashierTime[count] = 0; // load customer queue for (int count = 1; count <= NUM_CUSTOMERS; count++) customerQueue.add(new Customer(count * 15)); // arrival time Java Software Structures, 4th Edition, Lewis/Chase

Java Software Structures, 4th Edition, Lewis/Chase totalTime = 0; // process all customers in the queue while (!(customerQueue.isEmpty())) { for (int count = 0; count <= cashiers; count++) if (!(customerQueue.isEmpty())) customer = customerQueue.remove(); if (customer.getArrivalTime() > cashierTime[count]) start = customer.getArrivalTime(); else start = cashierTime[count]; departs = start + PROCESS_TIME; customer.setDepartureTime(departs); cashierTime[count] = departs; totalTime += customer.totalTime(); // total turnaround time } // output results for this simulation averageTime = totalTime / NUM_CUSTOMERS; System.out.println("Number of cashiers: " + (cashiers + 1)); System.out.println("Average time: " + averageTime + "\n"); Java Software Structures, 4th Edition, Lewis/Chase

Ticket Counter Simulation Java Software Structures, 4th Edition, Lewis/Chase

Ticket Counter Simulation The results of the simulation: With the goal of an average time of less than seven minutes (420 seconds), six cashiers will suffice Adding more than eight cashiers will not improve the situation Java Software Structures, 4th Edition, Lewis/Chase

A Queue ADT Defining our own interface for a queue, using only the classic operations: Java Software Structures, 4th Edition, Lewis/Chase

Java Software Structures, 4th Edition, Lewis/Chase package jsjf; /** * QueueADT defines the interface to a queue collection. * * @author Lewis and Chase * @version 4.0 */ public interface QueueADT<T> { * Adds one element to the rear of this queue. * @param element the element to be added to the rear of the queue public void enqueue(T element); * Removes and returns the element at the front of this queue. * @return the element at the front of the queue public T dequeue(); * Returns without removing the element at the front of this queue. * @return the first element in the queue public T first(); Java Software Structures, 4th Edition, Lewis/Chase

Java Software Structures, 4th Edition, Lewis/Chase /** * Returns true if this queue contains no elements. * @return true if this queue is empty */ public boolean isEmpty(); * Returns the number of elements in this queue. * @return the integer representation of the size of the queue public int size(); * Returns a string representation of this queue. * @return the string representation of the queue public String toString(); } Java Software Structures, 4th Edition, Lewis/Chase

Implementing a Queue with Links Since operations work on both ends of the queue, we'll use both front and rear references head first in first out tail element to be added at this end element to be removed from this end Java Software Structures, 4th Edition, Lewis/Chase

Implementing a Queue with Links After adding element E to the rear of the queue: read/tail front/head first in add E at the rear end Java Software Structures, 4th Edition, Lewis/Chase

Implementing a Queue with Links After removing an element from the front: head tail element at the front removed Java Software Structures, 4th Edition, Lewis/Chase

package jsjf; import jsjf. exceptions. ; / package jsjf; import jsjf.exceptions.*; /** * LinkedQueue represents a linked implementation of a queue. * * @author Lewis and Chase * @version 4.0 */ public class LinkedQueue<T> implements QueueADT<T> { private int count; private LinearNode<T> head, tail; // head: front, tail: rear * Creates an empty queue. public LinkedQueue() count = 0; head = tail = null; } Java Software Structures, 4th Edition, Lewis/Chase

head tail public void enqueue(T element) { /** * Adds the specified element to the tail of this queue. * @param element the element to be added to the tail of the queue */ public void enqueue(T element) { LinearNode<T> node = new LinearNode<T>(element); if (isEmpty()) head = node; else tail.setNext(node); // add the node to the tail (rear) tail = node; // update tail count++; } head tail 2 node 1 Java Software Structures, 4th Edition, Lewis/Chase

public T dequeue() throws EmptyCollectionException { if (isEmpty()) /** * Removes the element at the head of this queue and returns a * reference to it. * @return the element at the head of this queue * @throws EmptyCollectionException if the queue is empty */ public T dequeue() throws EmptyCollectionException { if (isEmpty()) throw new EmptyCollectionException("queue"); T result = head.getElement(); head = head.getNext(); // update head count--; tail = null; return result; } Java Software Structures, 4th Edition, Lewis/Chase

Implementing a Queue with an Array If we implement a queue as we did a stack, one end would be fixed at index 0: The problem is that (unlike a stack) a queue operates at both ends To be efficient, we must avoid shifting elements Java Software Structures, 4th Edition, Lewis/Chase

Implementing a Queue with an Array A better solution is to treat the array as circular A circular array is a a regular array that is treated as if it loops back around on itself That is, the last index is thought to precede index 0 We use two integers to keep track of where the front and rear of the queue are at any given time Java Software Structures, 4th Edition, Lewis/Chase

Implementing a Queue with an Array A queue implemented using a circular queue: front rear Java Software Structures, 4th Edition, Lewis/Chase

Implementing a Queue with an Array At some point, the elements of the queue may straddle the end of the array: front rear Java Software Structures, 4th Edition, Lewis/Chase

After A-H have been enqueued: front rear After A-H have been enqueued: After A-D have been dequeueed: After I, J, K, and L have been enqueued: rear front rear front Java Software Structures, 4th Edition, Lewis/Chase

Implementing a Queue with an Array Both the front and rear index values are incremented, wrapping back to 0 when necessary Java Software Structures, 4th Edition, Lewis/Chase

package jsjf; import jsjf. exceptions. ; / package jsjf; import jsjf.exceptions.*; /** * CircularArrayQueue represents an array implementation of a queue in * which the indexes for the front and rear of the queue circle back to 0 * when they reach the end of the array. * * @author Lewis and Chase * @version 4.0 */ public class CircularArrayQueue<T> implements QueueADT<T> { private final static int DEFAULT_CAPACITY = 100; private int front, rear, count; private T[] queue; Java Software Structures, 4th Edition, Lewis/Chase

/. Creates an empty queue using the specified capacity /** * Creates an empty queue using the specified capacity. * @param initialCapacity the initial size of the circular array queue */ public CircularArrayQueue (int initialCapacity) { front = rear = count = 0; queue = (T[]) (new Object[initialCapacity]); } * Creates an empty queue using the default capacity. public CircularArrayQueue() this(DEFAULT_CAPACITY); Java Software Structures, 4th Edition, Lewis/Chase

/. Adds the specified element to the rear of this queue, expanding /** * Adds the specified element to the rear of this queue, expanding * the capacity of the queue array if necessary. * @param element the element to add to the rear of the queue */ public void enqueue(T element) { if (size() == queue.length) expandCapacity(); queue[rear] = element; rear = (rear+1) % queue.length; count++; } Java Software Structures, 4th Edition, Lewis/Chase

/. Creates a new array to store the contents of this queue with /** * Creates a new array to store the contents of this queue with * twice the capacity of the old one. */ private void expandCapacity() { T[] larger = (T[]) (new Object[queue.length *2]); for (int scan = 0; scan < count; scan++) larger[scan] = queue[front]; front = (front + 1) % queue.length; } front = 0; rear = count; queue = larger; Java Software Structures, 4th Edition, Lewis/Chase

/. Removes the element at the front of this queue and returns a /** * Removes the element at the front of this queue and returns a * reference to it. * @return the element removed from the front of the queue * @throws EmptyCollectionException if the queue is empty */ public T dequeue() throws EmptyCollectionException { if (isEmpty()) throw new EmptyCollectionException("queue"); T result = queue[front]; queue[front] = null; front = (front+1) % queue.length; count--; return result; } Java Software Structures, 4th Edition, Lewis/Chase