Data Structures and Abstractions with Java 5 th
Data Structures and Abstractions with Java™ 5 th Edition Chapter 7 Queues, Deques, and Priority Queues Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
The ADT Queue • A queue is another name for a waiting line • Used within operating systems and to simulate real-world events – Come into play whenever processes or events must wait • Entries organized first-in, first-out Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
The ADT Queue FIGURE 7 -1 Some everyday queues Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
The ADT Queue • Terminology – Item added first, or earliest, is at the front of the queue – Item added most recently is at the back of the queue • Additions to a software queue must occur at its back • Client can look at or remove only the entry at the front of the queue Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
The ADT Queue • Data – A collection of objects in chronological order and having the same data type Pseudocode UML enqueue(new. Entry) +enqueue(new. Entry: integer): void dequeue() +dequeue(): T get. Front() +get. Front(): T is. Empty() +is. Empty(): boolean clear() +clear(): void Description Task: Adds a new entry to the back of the queue. Input: new. Entry is the new entry. Output: None. Task: Removes and returns the entry at the front of the queue. Input: None. Output: Returns the queue’s front entry. Throws an exception if the queue is empty before the operation. Task: Retrieves the queue’s front entry without changing the queue in any way. Input: None. Output: Returns the queue’s front entry. Throws an exception if the queue is empty. Task: Detects whether the queue is empty. Input: None. Output: Returns true if the queue is empty. Task: Removes all entries from the queue. Input: None. Output: None. Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
The ADT Queue /** An interface for the ADT queue. */ public interface Queue. Interface<T> { /** Adds a new entry to the back of this queue. @param new. Entry An object to be added. */ public void enqueue(T new. Entry); /** Removes and returns the entry at the front of this queue. @return The object at the front of the queue. @throws Empty. Queue. Exception if the queue is empty before the operation. */ public T dequeue(); /** Retrieves the entry at the front of this queue. @return The object at the front of the queue. @throws Empty. Queue. Exception if the queue is empty. */ public T get. Front(); /** Detects whether this queue is empty. @return True if the queue is empty, or false otherwise. */ public boolean is. Empty(); /** Removes all entries from this queue. */ public void clear(); } // end Queue. Interface LISTING 7 -1 An interface for the ADT queue Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
FIGURE 7 -2 The effect of operations on a queue of strings Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Simulating a Waiting Line FIGURE 7 -3 A line, or queue, of people Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Simulating a Waiting Line Wait. Line Responsibilities Simulate customers entering and leaving a waiting line Display number served, total wait time, average wait time, and number left in line Collaborations Customer FIGURE 7 -4 A CRC card for the class Wait. Line Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Simulating a Waiting Line Wait. Line 1 line—a queue of customers number. Of. Arrivals—number of customers number. Served—number of customers actually served total. Time. Waited—total time customers have waited simulate(duration, arrival. Probability, max. Transaction. Time) display. Results() Customer * arrival. Time transaction. Time customer. Number get. Arrival. Time() get. Transaction. Time() get. Customer. Number() FIGURE 7 -5 A diagram of the classes Wait. Line and Customer Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Simulating a Waiting Line Algorithm simulate(duration, arrival. Probability, max. Transaction. Time) transaction. Time. Left = 0 for (clock = 0; clock < duration; clock++) { if (a new customer arrives) { number. Of. Arrivals++ transaction. Time = a random time that does not exceed max. Transaction. Time next. Arrival = a new customer containing clock, transaction. Time, and a customer number that is number. Of. Arrivals line. enqueue(next. Arrival) } if (transaction. Time. Left > 0) // If present customer is still being served transaction. Time. Left−− else if (!line. is. Empty()) { next. Customer = line. dequeue() transaction. Time. Left = next. Customer. get. Transaction. Time() − 1 time. Waited = clock − next. Customer. get. Arrival. Time() total. Time. Waited = total. Time. Waited + time. Waited number. Served++ } } Algorithm for simulate Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Simulating a Waiting Line (Part 1) FIGURE 7 -6 A simulated waiting line Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Simulating a Waiting Line (Part 2) FIGURE 7 -6 A simulated waiting line Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Simulating a Waiting Line /** Simulates a waiting line. */ public class Wait. Line { private Queue. Interface<Customer> line; private int number. Of. Arrivals; private int number. Served; private int total. Time. Waited; public Wait. Line() { line = new Linked. Queue<>(); reset(); } // end default constructor LISTING 7 -2 The class Wait. Line /** Initializes the simulation. */ public final void reset() { line. clear(); number. Of. Arrivals = 0; number. Served = 0; total. Time. Waited = 0; } // end reset public void simulate(int duration, double arrival. Probability, int max. Transaction. Time) { < implementation on next slide > } public void display. Results() { < implementation on next slide > } } // end Wait. Line Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Simulating a Waiting Line public void simulate(int duration, double arrival. Probability, int max. Transaction. Time) { int transaction. Time. Left = 0; for (int clock = 0; clock < duration; clock++) { if (Math. random() < arrival. Probability) { number. Of. Arrivals++; int transaction. Time = (int)(Math. random() * max. Transaction. Time + 1); Customer next. Arrival = new Customer(clock, transaction. Time, number. Of. Arrivals); line. enqueue(next. Arrival); System. out. println("Customer " + number. Of. Arrivals + " enters line at time " + clock + ". Transaction time is " + transaction. Time); } // end if if (transaction. Time. Left > 0) transaction. Time. Left--; else if (!line. is. Empty()) { Customer next. Customer = line. dequeue(); transaction. Time. Left = next. Customer. get. Transaction. Time() - 1; int time. Waited = clock - next. Customer. get. Arrival. Time(); total. Time. Waited = total. Time. Waited + time. Waited; number. Served++; System. out. println("Customer " + next. Customer. get. Customer. Number() + " begins service at time " + clock + ". Time waited is " + time. Waited); } // end if } // end for } // end simulate Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Simulating a Waiting Line /** Displays summary results of the simulation. */ public void display. Results() { System. out. println(); System. out. println("Number served = " + number. Served); System. out. println("Total time waited = " + total. Time. Waited); double average. Time. Waited = ((double)total. Time. Waited) / number. Served; System. out. println("Average time waited = " + average. Time. Waited); int left. In. Line = number. Of. Arrivals - number. Served; System. out. println("Number left in line = " + left. In. Line); } // end display. Results Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Computing the Capital Gain in a Sale of Stock. Ledger Responsibilities Record the shares of a stock purchased, in chronological order Remove the shares of a stock sold, beginning with the ones held the longest Compute the capital gain (loss) on shares of a stock sold Collaborations Share of stock FIGURE 7 -7 A CRC card for the class Stock. Ledger Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Computing the Capital Gain in a Sale of Stock. Ledger 1 ledger—a collection of shares owned, in order of their time of purchase buy(shares. Bought, price. Per. Share) sell(shares. Sold, price. Per. Share) Stock. Purchases cost—cost of one share * get. Cost. Per. Share() FIGURE 7 -8 A diagram of the classes Stock. Ledger and Stock. Purchase Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Computing the Capital Gain in a Sale of Stock (Part 1) public class Stock. Ledger { private Queue. Interface<Stock. Purchase> ledger; public Stock. Ledger() { ledger = new Linked. Queue<>(); } // end default constructor /** Records a stock purchase in this ledger. @param shares. Bought The number of shares purchased. @param price. Per. Share The price per share. */ public void buy(int shares. Bought, double price. Per. Share) { while (shares. Bought > 0) { Stock. Purchase purchase = new Stock. Purchase(price. Per. Share); ledger. enqueue(purchase); shares. Bought--; } // end while } // end buy LISTING 7 -3 The class Stock. Ledger Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Computing the Capital Gain in a Sale of Stock (Part 2) /** Removes from this ledger any shares that were sold and computes the capital gain or loss. @param shares. Sold The number of shares sold. @param price. Per. Share The price per share. @return The capital gain (loss). */ public double sell(int shares. Sold, double price. Per. Share) { double sale. Amount = shares. Sold * price. Per. Share; double total. Cost = 0; while (shares. Sold > 0) { Stock. Purchase share = ledger. dequeue(); double share. Cost = share. get. Cost. Per. Share(); total. Cost = total. Cost + share. Cost; shares. Sold--; } // end while return sale. Amount - total. Cost; // Gain or loss } // end sell } // end Stock. Ledger LISTING 7 -3 The class Stock. Ledger Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
FIGURE 7 -9 Two representations of stock shares in a queue Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Java Class Library: The Interface Queue • Methods provided – add – offer – remove – poll – element – peek – is. Empty – size Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
The ADT Deque • A double ended queue • Deque pronounced “deck” • Has both queue-like operations and stack-like operations Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
The ADT Deque FIGURE 7 -10 An instance d of a deque Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
FIGURE 7 -11 A comparison of operations for a stack s, a queue q, and a deque d Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
The ADT Deque /** An interface for the ADT deque. */ public interface Deque. Interface<T> { /** Adds a new entry to the front/back of this deque. @param new. Entry An object to be added. */ public void add. To. Front(T new. Entry); public void add. To. Back(T new. Entry); /** Removes and returns the front/back entry of this deque. @return The object at the front/back of the deque. @throws Empty. Queue. Exception if the deque is empty before the operation. */ public T remove. Front(); public T remove. Back(); /** Retrieves the front/back entry of this deque. @return The object at the front/back of the deque. @throws Empty. Queue. Exception if the deque is empty. */ public T get. Front(); public T get. Back(); /** Detects whether this deque is empty. @return True if the deque is empty, or false otherwise. */ public boolean is. Empty(); /* Removes all entries from this deque. */ public void clear(); } // end Deque. Interface LISTING 7 -4 An interface for the ADT deque Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
The ADT Deque // Read a line d = a new empty deque while (not end of line) { character = next character read if (character == ←) d. remove. Back() else d. add. To. Back(character) } // Display the corrected line while (!d. is. Empty()) System. out. print(d. remove. Front()) System. out. println() Pseudocode that uses a deque to read and display a line of keyboard input Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Computing the Capital Gain in a Sale of Stock public double sell(int shares. Sold, double price. Per. Share) { double sale. Amount = shares. Sold * price. Per. Share; double total. Cost = 0; while (shares. Sold > 0) { Stock. Purchase transaction = ledger. remove. Front(); double share. Cost = transaction. get. Cost. Per. Share(); int number. Of. Shares = transaction. get. Number. Of. Shares(); if (number. Of. Shares > shares. Sold) { total. Cost = total. Cost + shares. Sold * share. Cost; int number. To. Put. Back = number. Of. Shares - shares. Sold; Stock. Purchase left. Over = new Stock. Purchase(number. To. Put. Back, share. Cost); ledger. add. To. Front(left. Over); // Return leftover shares // Note: Loop will exit since shares. Sold will be <= 0 later } else total. Cost = total. Cost + number. Of. Shares * share. Cost; shares. Sold = shares. Sold - number. Of. Shares; } // end while return sale. Amount - total. Cost; // Gain or loss } // end sell Method buy creates an instance of Stock. Purchase and places it at the back of the deque Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Java Class Library: The Interface Deque • Methods provided – add. First, offer. First – add. Last, offer. Last – remove. First, poll. First – remove. Last, poll. Last – get. First, peek. First – get. Last, peek. Last – is. Empty, clear, size – push, pop Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Java Class Library: The Class Array. Deque • Implements the interface Deque • Constructors provided – Array. Deque() – Array. Deque(int initial. Capacity) Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
ADT Priority Queue • Consider how a hospital assigns a priority to each patient that overrides time at which patient arrived. • ADT priority queue organizes objects according to their priorities • Definition of “priority” depends on nature of the items in the queue Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
ADT Priority Queue /** An interface for the ADT priority queue. */ public interface Priority. Queue. Interface<T extends Comparable<? super T>> { /** Adds a new entry to this priority queue. @param new. Entry An object to be added. */ public void add(T new. Entry); /** Removes and returns the entry having the highest priority. @return Either the object having the highest priority or, if the priority queue is empty before the operation, null. */ public T remove(); /** Retrieves the entry having the highest priority. @return Either the object having the highest priority or, if the priority queue is empty, null. */ public T peek(); /** Detects whether this priority queue is empty. @return True if the priority queue is empty, or false otherwise. */ public boolean is. Empty(); /** Gets the size of this priority queue. @return The number of entries currently in the priority queue. */ public int get. Size(); /** Removes all entries from this priority queue. */ public void clear(); } // end Priority. Queue. Interface LISTING 7 -5 An interface for the ADT priority queue Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Tracking Your Assignments Assignment course—the course code task—a description of the assignment date—the due date get. Course. Code() get. Task() get. Due. Date() compare. To() Assignment. Log log—a priority queue of assignments add. Project(new. Assignment) add. Project(course. Code, task, due. Date) get. Next. Project() remove. Next. Project() FIGURES 7 -12 & 7 -13 UML diagrams of the class Assignment and Assignment. Log Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Tracking Your Assignments public class Assignment. Log { private Priority. Queue. Interface<Assignment> log; public Assignment. Log() { log = new Priority. Queue<>(); } // end constructor public void add. Project(Assignment new. Assignment) { log. add(new. Assignment); } // end add. Project public void add. Project(String course. Code, String task, Date due. Date) { Assignment new. Assignment = new Assignment(course. Code, task, due. Date); add. Project(new. Assignment); } // end add. Project public Assignment get. Next. Project() { return log. peek(); } // end get. Next. Project public Assignment remove. Next. Project() { return log. remove(); } // end remove. Next. Project } // end Assignment. Log LISTING 7 -6 The class Assignment. Log Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Java Class Library: The Class Priority. Queue • Basic constructors and methods • Priority. Queue – add – offer – remove – poll – element – peek – is. Empty, clear, size Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
End Chapter 7 Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
- Slides: 36