230 likes | 376 Views
Queues, Deques, and Priority Queues. Chapter 14. Chapter Contents. Specifications for the ADT Queue Using a Queue to Simulate a Waiting Line The Classes WaitLine and Customer Using a Queue to Compute the capital Gain in a Sale of Stock The Classes StockLedger and StockPurchase
E N D
Queues, Deques, and Priority Queues Chapter 14
Chapter Contents • Specifications for the ADT Queue • Using a Queue to Simulate a Waiting Line • The Classes WaitLine and Customer • Using a Queue to Compute the capital Gain in a Sale of Stock • The Classes StockLedger and StockPurchase • Specifications of the ADT Deque • Using a Deque to Compute the Capital Gain in a Sale of Stock • Specifications of the ADT Priority Queue • Using a Priority Queue to Track Your Assignments
Specifications for the ADT Queue • Queue organizes entries according to order of entry, • Front of queue has items added first, end of queue has items added last. It organizes items chronologically • Exhibits first-in, first-out behavior • Contrast to stack which is last-in, first-out • All additions are at the back of the queue, removals are at the front of the queue.
Specifications for the ADT Queue Some everyday queues.
Specifications for the ADT Queue • Interface for a queue of objects public interface queueInterface{ /** Task: Adds a new entry to the back of the queue. * @param newEntry an object to be added */public void enqueue(Object newEntry); /** Task: Removes and returns the front of the queue. * @return either the object at the front of the queue or null if the queue was empty */public Object dequeue(); /** Task: Retrieves the front of the queue. * @return either the object at the front of the queue or null if the queue is empty */public Object getFront(); /** Task: Determines whether the queue is empty. * @return true if the queue is empty */public boolean isEmpty(); /** Task: Removes all entries from the queue. */public void clear();} // end queueInterface
Specifications for the ADT Queue Queue of strings after (a) enqueue adds Jim; (b) Jess; (c) Jill; (d) Jane; (e) Joe; (f) dequeue retrieves, removes Jim; (g) enqueue adds Jerry; (h) dequeue retrieves, removes Jess.
Using a Queue to Simulate a Waiting Line A line, or queue of people. Short waiting time increase satisfaction.
Waiting Line • Time-driven simulation, a counter enumerates simulated units of time - minutes etc. • Customers arrive at random times and are assigned a random transaction time. • Math.random(); • Maximal_transaction_time * Math.random() • At the conclusion, summary statistics are created including total number of customers served and the average waiting time.
Classes WaitLine and Customer A diagram of the classes WaitLine and Customer to generate a new customer
Classes WaitLine and Customer A simulated waiting line … continued →
Classes WaitLine and Customer (ctd) A simulated waiting line.
Pseudocode of Method Simulate Algorithm simulate (duration, arrivalProbability, maxTransactionTime) for( clock = 0; clock < duration; clock++) { if( a new customer arrives) { numberOfArrivals++ transactionTime = a random time does not exceed maxTransactionTime nextArrival = a new customer containing clock, transactionTime, and a customer number that is numberOfArrival line.enqueue(nextArrival) } if( transactionTimeLeft > 0 ) // if present customer is still being served transactionTimeLeft— else if(!line.isEmpty) { nextCustomer = line.dequeue() transactionTimeLeft = nextCustomer.getTransactionTime() -1 timeWaited = clock() – nextCustomer.getArrivalTime() totalTimeWaited = totalTimeWaited + timeWaited numberServed++ } }
Using a Queue to Compute Capital Gain in a Sale of Stock • Buy n shares of a stock for d dollars each. Later you sell some of these shares. • If the sale price exceeds the purchase price, you have made a profit - a capital gain. • Otherwise, you experience a loss. • Let’s assume you sell shares in the order in which you purchase them. ( first-in, first-out)
Using a Queue to Compute Capital Gain in a Sale of Stock • Must sell stocks in same order they were purchased • Must use the difference in selling price and purchase price to calculate capital gain • We use a queue to • Record investment transactions chronologically • Compute capital gain of the stock
Classes StockLedger and StockPurchase A diagram of the class StockLedger and StockPurchase.
30 shares at $45 eachtwo queues (a) Adds each of the 30 individual shares to a queue (b) Encapsulate 30 shares into one object If we only wan to sell 20 shares with 10 shares left. (a) is easy to implement. (b). Need to place 10 left shares to the front of the queue.
Specifications of the ADT Deque • A Double ended queue • At a post office, when it is your turn, you need to fill up a form, step aside and get served when finished. • Has operations that • Add, remove, or retrieve entries • At both its front and back • Combines and expands the operations of queue and stack
Specifications of the ADT Deque An instance of a deque.
Specifications of the ADT Deque • A Java interface public interface DequeInterface{ public void addToFront(Object newEntry);public void addToBack(Object newEntry);public Object removeFront();public Object removeBack();public Object getFront();public Object getBack();public boolean isEmpty();public void clear();} // end DequeInterface
Specifications of the ADT Deque A comparison of the operations that add, remove, and retrieve the entries of a stack s, queue q, and a deque d; (a) add; (b) remove; (c) retrieve.
Specifications of the ADT Priority Queue • Organizes objects according to priorities • Contrast to regular queue in order of arrival • Priority queue example – a hospital ER: assign a priority number to each patient to override the arrival time. • Priority can be specified by an integer • Must define whether high number is high priority or … • Low number (say 0) is high priority • Other objects can specify priority • Object must have a compareTo method
Specifications of the ADT Priority Queue public interface PriorityQueueInterface{ public void add(Comparable newEntry); public Comparable remove();public Comparable get();public boolean isEmpty();public int getSize();public void clear();} // end PriorityQueueInterface
Using Priority Queue to Track Your Assignment • Class TrackAssignment • Include data field DueDate • Method compareTo is made available • This field is the priority – earliest due date is highest priority • Organize tasks in the order in which we should complete them.