queues.ppt
Transcript of queues.ppt
-
QueuesBriana B. MorrisonAdapted from Alan Eugenio
Queues
-
TopicsDefine QueueAPIsApplicationsRadix SortSimulationImplementationArray basedCircularEmpty, one value, fullLinked list basedDequesPriority Queues
Queues
-
Queues
A QUEUE IS A CONTAINER IN WHICH:
.INSERTIONS ARE MADE ONLY AT
THE BACK;
.DELETIONS, RETRIEVALS, AND
MODIFICATIONS ARE MADE ONLY
AT THE FRONT.
-
The QueueA Queue is a FIFO (First in First Out) Data Structure. Elements are inserted in the Rear of the queue and are removed at the Front.
Queues
-
Queues
PUSH (ALSO CALLED ENQUEUE) -- TO INSERT AN ITEM AT THE BACK
POP (ALSO CALLED DEQUEUE) -- TO DELETE THE FRONT ITEM
IN A QUEUE, THE FIRST ITEM
INSERTED WILL BE THE FIRST ITEM
DELETED: FIFO (FIRST-IN, FIRST-OUT)
-
Queues
METHOD INTERFACES
FOR THE
queue CLASS
-
Queues
-
Queues
-
void push(const T& item);Insert the argument item at the back of the queue.Postcondition:The queue has a new item at the backint size() const;Return the number of elements in the queue.
Queues
-
Queues
THERE ARE NO ITERATORS!
THE ONLY ACCESSIBLE ITEM IS THE
FRONT ITEM.
-
DETERMINE THE OUTPUT FROM THE FOLLOWING:
queue my_queue;
for (int i = 0; i < 10; i++) my_queue.push (i * i);
while (!my_queue.empty()){ cout
-
Queues
THE queue CLASS IS TEMPLATED:
template
T IS THE TEMPLATE PARAMETER
FOR THE ITEM TYPE. Container IS THE
TEMPLATE PARAMETER FOR THE
CLASS THAT WILL HOLD THE ITEMS,
WITH THE deque CLASS THE DEFAULT.
-
Queues
THE queue CLASS IS A CONTAINER
ADAPTOR. A CONTAINER ADAPTOR C
CALLS THE METHODS FROM SOME
OTHER CLASS TO DEFINE THE
METHODS IN C.
-
deque?
list?
vector? OKOKNOT OK: NO pop_front METHOD
Queues
SPECIFICALLY, THE queue CLASS
ADAPTS ANY CONTAINER CLASS
THAT HAS push_back, pop_front, front,
size, AND empty METHODS.
-
Implementing Queue: adapter of std::listThis is a simple adapter class, with following mappings:Queue push maps to push_backQueue front maps frontQueue pop maps to pop_front ...This is the approach taken by the C++ standard library.Any sequential container that supports push_back, front, and pop_front can be used.The listThe deque
Queues
-
Queues
THE STANDARD C++ REQUIRES THAT
THE DEFINITION OF THE queue
CLASS INCLUDE
protected:
Container c;
-
Queues
ALSO, THE METHOD DEFINITIONS
ARE PRESCRIBED. FOR EXAMPLE,
public:
void push (const value_type& x) { c.push_back (x)); }
void pop( ) { c.pop_front( ); }
const T& front( ) const { return c.front( ); }
-
Queues
-
Queues
IF EITHER A DEQUE OR LIST IS THE
UNDERLYING CONTAINER,
worstTime(n) IS CONSTANT FOR EACH
METHOD.
EXCEPTION: FOR THE push METHOD,
IF A DEQUE IS THE UNDERLYING
CONTAINER, worstTime(n) IS LINEAR IN
n, AND averageTime(n) IS CONSTANT
(AND amortizedTime(n) IS CONSTANT).
-
Applications of QueuesDirect applicationsWaiting lists, bureaucracyAccess to shared resources (e.g., printer)MultiprogrammingIndirect applicationsAuxiliary data structure for algorithmsComponent of other data structures
Queues
-
Queues
APPLICATION OF QUEUES:
RADIX SORT
-
The Radix SortOrder ten 2 digit numbers in 10 bins from smallest number to largest number. Requires 2 calls to the sort Algorithm.Initial Sequence:91 6 85 15 92 35 30 22 39Pass 0: Distribute the cards into bins according to the 1's digit (100).
Queues
-
The Radix SortAfter Collection:30 91 92 22 85 15 35 6 39Pass 1: Take the new sequence and distribute the cards into bins determined by the 10's digit (101).Final Sequence:6 15 22 30 35 39 85 91 92
Queues
-
Radix SortUse an array of queues (or vector of queues) as the bucketsvoid radixSort (vector& v, int d){int i;int power = 1;queue digitQueue[10];
for (i=0;i < d;i++){distribute(v, digitQueue, power);collect(digitQueue, v);power *= 10;}}
Queues
-
// support function for radixSort()// distribute vector elements into one of 10 queues// using the digit corresponding to power// power = 1 ==> 1's digit// power = 10 ==> 10's digit// power = 100 ==> 100's digit// ...void distribute(const vector& v, queue digitQueue[], int power){int i;
// loop through the vector, inserting each element into// the queue (v[i] / power) % 10for (i = 0; i < v.size(); i++)digitQueue[(v[i] / power) % 10].push(v[i]);}
Queues
-
// support function for radixSort()// gather elements from the queues and copy back to the vectorvoid collect(queue digitQueue[], vector& v){int i = 0, digit;
// scan the vector of queues using indices 0, 1, 2, etc.for (digit = 0; digit < 10; digit++)// collect items until queue empty and copy items back// to the vectorwhile (!digitQueue[digit].empty()){v[i] = digitQueue[digit].front();digitQueue[digit].pop();i++;}}
Queues
-
Queues
APPLICATION OF QUEUES:
COMPUTER SIMULATION
-
A SYSTEM IS A COLLECTION OF INTERACTING PARTS.A MODEL IS A SIMPLIFICATION OF A SYSTEM.THE PURPOSE OF BUILDING A MODEL IS TO STUDY THE UNDERLYING SYSTEM.
Queues
-
Queues
PHYSICAL MODEL: DIFFERS FROM
THE SYSTEM ONLY IN SCALE OR
INTENSITY.
EXAMPLES: WAR GAMES, PRE-SEASON
-
Queues
MATHEMATICAL MODEL: A SET OF
EQUATIONS, VARIABLES, AND
ASSUMPTIONS
-
Queues
A
500
D
? 200
500 C
B 400 E
ASSUMPTIONS: ANGLE ADC = ANGLE BCD
BEC FORMS A RIGHT TRIANGLE
DCE FORMS A STRAIGHT LINE
LINE SEGMENT AB PARALLEL TO DC
DISTANCE FROM A TO B?
-
Queues
IF IT IS INFEASIBLE TO SOLVE THE
MATH MODEL (THAT IS, THE
EQUATIONS) BY HAND, A PROGRAM
IS DEVELOPED.
COMPUTER SIMULATION: THE
DEVELOPMENT OF COMPUTER
PROGRAMS TO SOLVE MATH MODELS
-
Queues
DEVELOP
System Computer
Model
VERIFY RUN
Interpretation Output
DECIPHER
-
Queues
IF THE INTERPRETATION DOES NOT
CORRESPOND TO THE BEHAVIOR OF
THE SYSTEM, CHANGE THE MODEL!
-
Simulating Waiting Lines Using QueuesSimulation is used to study the performance:Of a physical (real) systemBy using a physical, mathematical, or computer model of the systemSimulation allows designers to estimate performanceBefore building a systemSimulation can lead to design improvementsGiving better expected performance of the system
Queues
-
Simulating Waiting Lines Using QueuesSimulation is particular useful when:Building/changing the system is expensiveChanging the system later may be dangerousOften use computer models to simulate real systemsAirline check-in counter, for exampleSpecial branch of mathematics for these problems:Queuing Theory
Queues
-
Simulate Strategies for Airline Check-In
Queues
-
Simulate Airline Check-InWe will maintain a simulated clockCounts in integer ticks, from 0At each tick, one or more events can happen:Frequent flyer (FF) passenger arrives in lineRegular (R) passenger arrives in lineAgent finishes, then serves next FF passengerAgent finishes, then serves next R passengerAgent is idle (both lines empty)
Queues
-
Simulate Airline Check-InSimulation uses some parameters:Max # FF served between regular passengersArrival rate of FF passengersArrival rate of R passengersService timeDesired output:Statistics on waiting times, agent idle time, etc.Optionally, a detailed trace
Queues
-
Simulate Airline Check-InDesign approach:Agent data type models airline agentPassenger data type models passengers2 queue, 1 for FF, 1 for ROverall Airline_Checkin_Sim class
Queues
-
Simulate Airline Check-In
Queues
-
Queues
QUEUE PRIVATE APPLICATION
A SIMULATED CAR WASHtc \l 4 "QUEUE APPLICATION\: A SIMULATED CAR WASH"
xe "Queue Application"
-
Queues
PROBLEM:
GIVEN THE ARRIVAL TIMES AT
SPEEDYS CAR WASH, CALCULATE THE
AVERAGE WAITING TIME PER CAR.
-
Queues
ANALYSIS:
ONE WASH STATION
10 MINUTES FOR EACH CAR TO GET
WASHED
AT ANY TIME, AT MOST 5 CARS
WAITING TO BE WASHED; ANY OTHERS
TURNED AWAY AND NOT COUNTED
-
Queues
AVERAGE WAITING TIME = SUM OF
WAITING TIMES / NUMBER OF CARS
IN A GIVEN MINUTE, A DEPARTURE IS
PROCESSED BEFORE AN ARRIVAL.
-
Queues
IF A CAR ARRIVES WHEN NO CAR IS
BEING WASHED AND NO CAR IS
WAITING, THE CAR IMMEDIATELY
ENTERS THE WASH STATION.
A CAR STOPS WAITING WHEN IT
ENTERS THE WASH STATION.
SENTINEL IS 999.
-
Queues
SYSTEM TEST 1:
8
11
11
13
14
16
16
20
999
-
Queues
TIME
EVENT
WAITING TIME
8
ARRIVAL
11 ARRIVAL
11 ARRIVAL
13
ARRIVAL
14 ARRIVAL
16 ARRIVAL
16
ARRIVAL (OVERFLOW)
18
DEPARTURE
0
20 ARRIVAL
28
DEPARTURE
7
38
DEPARTURE
17
48
DEPARTURE
25
58
DEPARTURE
34
68
DEPARTURE
42
78
DEPARTURE
48
-
Queues
AVERAGE WAITING TIME
= 173 / 7.0 MINUTES
= 24.7 MINUTES
-
Queues
CAR WASH APPLET
http://www.cs.lafayette.edu/~collinsw/carwash/car.html
-
Implementing a QueueArray basedWhere is front? Where is top?Array suffers from rightward driftTo solve, use circular array
How are elements added, removed?Using circular array, a new problem arisesWhat does empty look like?What does single element look like?What does full look like?
Queues
-
Array-based QueueUse an array of size N in a circular fashionTwo variables keep track of the front and rearf index of the front elementrindex immediately past the rear elementArray location r is kept emptynormal configurationwrapped-around configuration
Queues
-
Implementing queue With a Circular ArrayBasic idea: Maintain two integer indices into an arrayfront: index of first element in the queuerear: index of the last element in the queueElements thus fall at front through rearKey innovation:If you hit the end of the array wrap around to slot 0This prevents our needing to shift elements around
Still have to deal with overflow of space
Queues
-
Implementing Queue With Circular Array
Queues
-
Implementing Queue With Circular Array
Queues
-
Implementing Queue With Circular Array
Queues
-
The Bounded queue
Queues
-
Methods to Implementi = (( i + 1) == max) ? 0 : (i + 1);
if (( i + 1) == max) i = 0; else i = i + 1;
i = ( i + 1) % max;
Queues
-
Queue OperationsWe use the modulo operator (remainder of division)Algorithm size()return (N - f + r) mod N
Algorithm isEmpty()return (f = r)
Queues
-
Queue Operations (cont.)Operation enqueue throws an exception if the array is fullThis exception is implementation-dependentAlgorithm enqueue(o)if size() = N 1 thenthrow FullQueueException else Q[r] or (r + 1) mod N
Queues
-
Queue Operations (cont.)Operation dequeue throws an exception if the queue is emptyThis exception is specified in the queue ADTAlgorithm dequeue()if isEmpty() thenthrow EmptyQueueException elseo Q[f]f (f + 1) mod Nreturn o
Queues
-
Boundary Conditions
Queues
-
Implementation ConsiderationsThe physical model: a linear array with the front always in the first position and all entries moved up the array whenever the front is deleted.A linear array with two indices always increasing.A circular array with front and rear indices and one position left vacant.A circular array with front and rear indices and a Boolean flag to indicate fullness (or emptiness).A circular array with front and rear indices and an integer counter of entries.A circular array with front and rear indices taking special values to indicate emptiness.
Queues
-
Growable Array-based QueueIn an enqueue operation, when the array is full, instead of throwing an exception, we can replace the array with a larger oneSimilar to what we did for an array-based stackThe enqueue operation has amortized running time O(n) with the incremental strategy O(1) with the doubling strategy
Queues
-
Implementing a QueueLinked List basedWhere is front? Where is back?How are elements added, removed?
Efficiency of operations
Queues
-
Queue with a Singly Linked ListWe can implement a queue with a singly linked listThe front element is stored at the first nodeThe rear element is stored at the last nodeThe space used is O(n) and each operation of the Queue ADT takes O(1) timefrnodeselements
Queues
-
Implementing Queue: Singly-Linked ListThis requires front and rear Node pointers: template class queue { . . . private: // Insert implementation-specific data fields // Insert definition of Node here #include "Node.h" // Data fields Node* front_of_queue; Node* back_of_queue; size_t num_items; };
Queues
-
Using a Single-Linked List to Implement a Queue (continued)
Queues
-
Implementing Queue: Singly-Linked ListInsert at tail, using back_of_queue for speedRemove using front_of_queueAdjust size when adding/removingNo need to iterate through to determine size
Queues
-
Analysis of the Space/Time IssuesTime efficiency of singly- or doubly-linked list good:O(1) for all Queue operationsSpace cost: ~3 extra words per itemvector uses 1 word per item when fully packed2 words per item when just grownOn average ~1.5 words per item, for larger lists
Queues
-
Comparing the Three ImplementationsAll three are comparable in time: O(1) operationsLinked-lists require more storageSingly-linked list: ~3 extra words / elementDoubly-linked list: ~4 extra words / elementCircular array: 0-1 extra word / elementOn average, ~0.5 extra word / element
Queues
-
Analysis of the Space/Time Issuesvector ImplementationInsertion at end of vector is O(1), on averageRemoval from the front is linear time: O(n)Removal from rear of vector is O(1)Insertion at the front is linear time: O(n)
Queues
-
Queues
DEQUES
Double Ended Queues
-
Queues
A DEQUE IS A FINITE SEQUENCE OF
ITEMS SUCH THAT
1. GIVEN ANY INDEX, THE ITEM IN THE SEQUENCE AT THAT INDEX CAN BE ACCESSED OR MODIFIED IN CONSTANT TIME.
2. AN INSERTION OR DELETION AT THE FRONT OR BACK OF THE SEQUENCE TAKES ONLY CONSTANT TIME, ON AVERAGE.
-
Queues
THE deque CLASS IS VERY SIMILAR TO
THE vector CLASS.
-
The dequeThe deque is an abstract data type that combines the features of a stack and a queue.The name deque is an abbreviation for double-ended queue.The C++ standard defines the deque as a full-fledged sequential container that supports random access.
Queues
-
The deque class
Queues
Member Function
Behavior
const Item_Type&operator[](size_t index)const;
Item_Type&operator[](size_t index)
Returns a reference to the element at position index.
const Item_Type&at(size_t index) const;
Item_Type&at(size_t index)
Returns a reference to the element at position index. If index is not valid, the out_of_range exception is thrown.
iterator insert(iterator pos, const Item_Type& item)
Inserts a copy of item into the deque at position pos. Returns an iterator that references the newly inserted item.
iterator erase(iterator pos)
Removes the item from the deque at position pos. Returns an iterator that references the item following the one erased.
void remove(const Item_Type& item)
Removes all occurrences of item from the deque.
-
The deque class (2)
Queues
Member Function
Behavior
void push_front(const Item_Type& item)
Inserts a copy of item as the first element of the deque
void push_back(const Item_Type& item)
Inserts a copy of item as the last element of the deque.
void pop_front()
Removes the first item from the deque.
void pop_back()
Removes the last item from the deque.
Item_Type& front();
const Item_Type& front() const
Returns a reference to the first item in the deque.
Item_Type& back();
const Item_Type& back() const
Returns a reference to the last item in the deque.
iterator begin()
Returns an iterator that references the first item of the deque.
const_iterator begin() const
Returns a const_iterator that references the first item of the deque.
-
The deque class (3)
Queues
Member Function
Behavior
iterator end()
Returns an iterator that references one past the last item of the deque.
const_iterator end() const
Returns a const_iterator that references one past the last item of the deque.
void swap(deque
-
Queues
TO TAKE ADVANTAGE OF INSERTIONS AND DELETIONS AT THE FRONT OF A DEQUE, THERE ARE TWO METHODS:
// Postcondition: A copy of x has been inserted at the front
// of this deque. The averageTime(n) is
// constant, and worstTime (n) is O(n) but
// for n consecutive insertions,
// worstTime(n) is only O(n). That is,
// amortizedTime(n) is constant.
void push_front (const T& x);
// Postcondition: The item at the front of this deque has
// been deleted.
void pop_front( );
-
Queues
THE deque CLASS ALSO HAS ALL OF
THE METHODS FROM THE vector CLASS
(EXCEPT FOR capacity AND reserve),
AND THE INTERFACES ARE THE SAME!
-
Whats output?
Queues
dequewords;
string word;
for (int i = 0; i < 5; i++)
{
cin >> word;
words.push_back (word);
} // for
words.pop_front( );
words.pop_back( );
for (unsigned i = 0; i < words.size(); i++)
cout
-
Queues
ON PAPER, THAT IS, LOOKING AT BIG-
O TIME ESTIMATES ONLY, A DEQUE IS
SOMETIMES FASTER AND NEVER
SLOWER THAN A VECTOR.
-
Queues
IN PRACTICE, THAT IS, LOOKING AT
RUN-TIMES, VECTORS ARE FASTER
EXCEPT FOR INSERTIONS AND
DELETIONS AT OR NEAR THE FRONT,
AND THERE DEQUES ARE MUCH
FASTER THAN VECTORS.
-
The Standard Library ImplementationThe standard library uses a randomly accessible circular array.Each item in the circular array points to a fixed size, dynamically allocated array that contains the data.The advantage of this implementation is that when reallocation is required, only the pointers need to be copied into the new circular array.
Queues
-
The Standard Library Implementation (2)
Queues
-
Queues
IN THE HEWLETT-PACKARD DESIGN
AND IMPLEMENTATION OF THE deque
CLASS, THERE IS A map FIELD: A
POINTER TO AN ARRAY. THE ARRAY
ITSELF CONTAINS POINTERS TO
BLOCKS THAT HOLD THE ITEMS. THE
start AND finish FIELDS ARE
ITERATORS.
-
Queues
map start
finish
yes
true
now
good
love
clear
right
-
Queues
FOR CONTAINER CLASSES IN
GENERAL, ITERATORS ARE SMART
POINTERS. FOR EXAMPLE operator++
ADVANCES TO THE NEXT ITEM,
WHICH MAY BE AT A LOCATION FAR
AWAY FROM THE CURRENT ITEM.
-
Queues
DEQUE ITERATORS ARE GENIUSES!
-
Queues
THE iterator CLASS EMBEDDED IN THE deque CLASS HAS FOUR FIELDS:
1. first, A POINTER TO THE BEGINNING OF THE BLOCK;
2. current, A POINTER TO AN ITEM;
3. last, A POINTER TO ONE BEYOND THE END OF THE BLOCK;
4. node, A POINTER TO THE LOCATION IN THE MAP ARRAY THAT POINTS TO THE BLOCK.
-
Queues
map start
finish
yes
true
now
good
love
clear
right
-
Queues
SUPPOSE THE DEQUE SHOWN IN THE
PREVIOUS SLIDE IS words. HOW DOES
RANDOM ACCESS WORK? FOR
EXAMPLE, HOW IS words [5]
ACCESSED?
-
Queues
1. BLOCK NUMBER
= (index + offset of first item in first block) / block size
= (5 + start.current start.first) / 4
= (5 + 2) / 4
= 1
2. OFFSET WITHIN BLOCK
= (index+offset of first item in first block) % block size
= 7 % 4
= 3
-
Queues
THE ITEM AT words [5], AT AN OFFSET
OF 3 FROM THE START OF BLOCK 1, IS
clear.
-
Queues
FOR AN INSERTION OR REMOVAL AT
SOME INDEX i IN THE INTERIOR OF A
DEQUE, THE NUMBER OF ITEMS
MOVED IS THE MINIMUM OF i AND
length i. THE length FIELD CONTAINS
THE NUMBER OF ITEMS.
-
Queues
FOR EXAMPLE, TO INSERT AT words [5],
THE NUMBER OF ITEMS MOVED IS 7 5
= 2.
TO DELETE THE ITEM AT INDEX 1, THE
NUMBER OF ITEMS MOVED IS 1.
-
Queues
EXERCISE: SUPPOSE, FOR SOME deque
CONTAINER, BLOCK SIZE = 10 AND
THE FIRST ITEM IS AT INDEX 7 IN
BLOCK 0. DETERMINE THE BLOCK
AND OFFSET FOR INDEX 31.
-
Priority QueueA Special form of queue from which items are removed according to their designated priority and not the order in which they entered.Items entered the queue in sequential order but will be removed in the order #2, #1, #4, #3.
Queues
-
Queues
-
void push(const T& item);Insert the argument item into the priority queue.Postcondition: The priority queue contains a new element.int size() const;Return the number of items in the priority queue.T& top();Return a reference to the item having the highest priority.Precondition: The priority queue is not empty.const T& top();Constant version of top().
Queues
-
PQ ImplementationHow would you implement a priority queue?
Queues
-
Summary Slide 1*-Queue-A first-come-first-served data structure. - Insertion operations (push()) occur at the back of the sequence - deletion operations (pop()) occur at the front of the sequence.
Queues
-
Summary Slide 2*-The radix sort algorithm-Orders an integer vector by using queues (bins).-This sorting technique has running time O(n) but has only specialized applications.-The more general in-place O(n log2n) sorting algorithms are preferable in most cases.
Queues
-
Summary Slide 3*-Implementing a queue with a fixed-size array-Indices qfront and qback move circularly around the array.-Gives O(1) time push() and pop() operations with no wasted space in the array.
Queues
-
Summary Slide 4*-Priority queue-Pop() returns the highest priority item (largest or smallest).-Normally implemented by a heap, which is discussed later in the class.-The push() and pop() operations have running time O(log2n)
Queues