Queues

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 106

Queues

Briana B. Morrison
Adapted from Alan Eugenio

Topics

Define Queue
APIs
Applications

Radix Sort
Simulation

Implementation

Array based

Circular

Empty, one value, full

Linked list based

Deques
Priority 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.

Queues

The Queue
A

push A

fro nt
back

fro nt

back

fro nt

fro nt

back

fro nt
back

C
back

B
C

push B
push C
pop A

A 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.

pop B
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

CLASS queue

Constructor

<queue>

Operations

<queue>

queue();
Create an empty queue.
CLASS queue

bool empty() const;


Check whether the queue is empty. Return true if it is
empty and false otherwise.
T& front();
Return a reference to the value of the item at the font
of the queue.
Precondition: The queue is not empty.
Queues

CLASS queue

Operations

<queue>

const T& front() const;


Constant version of front().
void pop();
Remove the item from the front of the queue.
Precondition: The queue is not empty.
Postcondition: The element at the front of the queue
is the element that was added
immediately after the element just
popped or the queue is empty.

Queues

CLASS queue

Operations

<queue>

void push(const T& item);


Insert the argument item at the back of the queue.
Postcondition: The queue has a new item at the back
int size() const;
Return the number of elements in the queue.

Queues

THERE ARE NO ITERATORS!


THE ONLY ACCESSIBLE ITEM IS THE
FRONT ITEM.
Queues

10

DETERMINE THE OUTPUT FROM THE


FOLLOWING:
queue<int> my_queue;
for (int i = 0; i < 10; i++)
my_queue.push (i * i);
while (!my_queue.empty())
{
cout << my_queue.front() << endl;
my_queue.pop();
} // while
Queues

11

THE queue CLASS IS TEMPLATED:


template <class T, class Container = deque<T> >

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

12

THE queue CLASS IS A CONTAINER


ADAPTOR. A CONTAINER ADAPTOR C
CALLS THE METHODS FROM SOME
OTHER CLASS TO DEFINE THE
METHODS IN C.

Queues

13

deque?

OK

list?

OK

vector?

NOT OK: NO pop_front METHOD

Queues

14

Implementing Queue: adapter of


std::list

This is a simple adapter class, with following mappings:

Queue push maps to push_back


Queue front maps front
Queue 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 list
The deque
Queues

15

THE STANDARD C++ REQUIRES THAT


THE DEFINITION OF THE queue
CLASS INCLUDE
protected:
Container c;

Queues

16

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

17

m in iQ u e u e < in t> m in iQ ; // d e c la r e a n e m p ty q u e u e
Q u e u e S ta te m e n t

m in iQ .p u s h (1 0 )

Q ueue

L is t S ta te m e n t
q lis t.p u s h _ b a c k (1 0 )

10

fr o n tb a c k
m in iQ .p u s h (2 5 )

10

10

10

fro n t b a c k
q lis t.p u s h _ b a c k (2 5 )

25

fr o n t b a c k
m in iQ .p u s h (5 0 )

L is t

25

fr o n t

fro n t
10

back

fr o n t
r e tu r n q lis t.fr o n t()

m in iQ .p o p ()

q lis t.p o p _ fr o n t()

50

fr o n t

back

Queues

back
25

50

n = m in iQ .fr o n t() // n = 1 0
25

25

10

50

back

// r e tu r n 1 0
25

50

18

Queues

19

Applications of Queues

Direct applications

Waiting lists, bureaucracy


Access to shared resources (e.g., printer)
Multiprogramming

Indirect applications

Auxiliary data structure for algorithms


Component of other data structures

Queues

20

Queues

21

The Radix Sort

Order 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 39
Pass 0:
Distribute the cards into bins according
to the 1's digit (100).

30

91

22
92

35
15
85

Queues

39

22

The Radix Sort

After Collection: 30 91 92 22 85 15 35 6 39
Pass 1: Take the new sequence and distribute the
cards into bins determined by the 10's digit (10 1).
Final Sequence: 6 15 22 30 35 39 85 91 92

15

22

39
35
30

6
Queues

85

92
91

9
23

Radix Sort
Use an array of queues (or vector of queues) as the buckets
void radixSort (vector<int>& v, int d)
{
int i;
int power = 1;
queue<int> digitQueue[10];

for (i=0;i < d;i++)


{
distribute(v, digitQueue, power);
collect(digitQueue, v);
power *= 10;
}
}

Queues

24

// 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<int>& v, queue<int> digitQueue[],
int power)
{
int i;
// loop through the vector, inserting each element into
// the queue (v[i] / power) % 10
for (i = 0; i < v.size(); i++)
digitQueue[(v[i] / power) % 10].push(v[i]);
}

Queues

25

// support function for radixSort()


// gather elements from the queues and copy back to the vector
void collect(queue<int> digitQueue[], vector<int>& 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 vector
while (!digitQueue[digit].empty())
{
v[i] = digitQueue[digit].front();
digitQueue[digit].pop();
i++;
}
}

Queues

26

APPLICATION OF QUEUES:
COMPUTER SIMULATION

Queues

27

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

28

PHYSICAL MODEL: DIFFERS FROM


THE SYSTEM ONLY IN SCALE OR
INTENSITY.

EXAMPLES: WAR GAMES, PRE-SEASON

Queues

29

MATHEMATICAL MODEL: A SET OF


EQUATIONS, VARIABLES, AND
ASSUMPTIONS

Queues

30

A
500
D
?

200
500
B

400

C
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

31

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

32

System

DEVELOP

VERIFY

Interpretation

Computer
Model
RUN

DECIPHER

Queues

Output

33

IF THE INTERPRETATION DOES NOT


CORRESPOND TO THE BEHAVIOR OF
THE SYSTEM, CHANGE THE MODEL!

Queues

34

Simulating Waiting Lines Using


Queues

Simulation is used to study the performance:

Simulation allows designers to estimate


performance

Of a physical (real) system


By using a physical, mathematical, or computer model
of the system

Before building a system

Simulation can lead to design improvements

Giving better expected performance of the system


Queues

35

Simulating Waiting Lines


Using Queues

Simulation is particular useful when:

Building/changing the system is expensive


Changing the system later may be dangerous

Often use computer models to simulate real


systems

Airline check-in counter, for example


Special branch of mathematics for these problems:
Queuing Theory
Queues

36

Simulate Strategies for Airline


Check-In

Queues

37

Simulate Airline Check-In

We will maintain a simulated clock

1.
2.
3.

4.

5.

Counts in integer ticks, from 0

At each tick, one or more events can


happen:
Frequent flyer (FF) passenger arrives in line
Regular (R) passenger arrives in line
Agent finishes, then serves next FF
passenger
Agent finishes, then serves next R
passenger
Agent is idle (both lines empty)
Queues

38

Simulate Airline Check-In

Simulation uses some parameters:

Max # FF served between regular passengers


Arrival rate of FF passengers
Arrival rate of R passengers
Service time

Desired output:

Statistics on waiting times, agent idle time, etc.


Optionally, a detailed trace
Queues

39

Simulate Airline Check-In

Design approach:

Agent data type models airline agent


Passenger data type models passengers
2 queue<Passenger>, 1 for FF, 1 for R
Overall Airline_Checkin_Sim class

Queues

40

Simulate Airline Check-In

Queues

41

QUEUE APPLICATION
A SIMULATED CAR WASH
Queues

42

PROBLEM:
GIVEN THE ARRIVAL TIMES AT
SPEEDYS CAR WASH, CALCULATE THE
AVERAGE WAITING TIME PER CAR.

Queues

43

Queues

44

AVERAGE WAITING TIME = SUM OF


WAITING TIMES / NUMBER OF CARS
IN A GIVEN MINUTE, A DEPARTURE IS
PROCESSED BEFORE AN ARRIVAL.
Queues

45

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

46

SYSTEM TEST 1:
8
11
11
13
14
16
16
20
999
Queues

47

TIME
8
11
11
13
14
16
16
18
20
28
38
48
58
68
78

EVENT
WAITING TIME
ARRIVAL
ARRIVAL
ARRIVAL
ARRIVAL
ARRIVAL
ARRIVAL
ARRIVAL (OVERFLOW)
DEPARTURE
0
ARRIVAL
DEPARTURE
7
DEPARTURE
17
DEPARTURE
25
DEPARTURE
34
DEPARTURE
42
Queues 48
DEPARTURE

48

AVERAGE WAITING TIME


= 173 / 7.0 MINUTES
= 24.7 MINUTES
Queues

49

CAR WASH APPLET


http://www.cs.lafayette.edu/~collinsw/carwash/car.html

Queues

50

Implementing a Queue

Array based

Where is front? Where is top?

Array suffers from rightward drift


To solve, use circular array

How are elements added, removed?

Using circular array, a new problem arises


What does empty look like?
What does single element look like?
What does full look like?
Queues

51

Array-based Queue

Use an array of size N in a circular fashion


Two variables keep track of the front and rear
f index of the front element
r index immediately past the rear element

Array location r is kept empty

normal configuration
Q
0 1 2

wrapped-around configuration
Q
0 1 2

f
Queues

52

Implementing queue With a


Circular Array
Basic idea: Maintain two integer indices into an array
front: index of first element in the queue
rear: index of the last element in the queue
Elements thus fall at front through rear
Key innovation:
If you hit the end of the array wrap around to slot 0
This prevents our needing to shift elements around

Still have to deal with overflow of space


Queues

53

Implementing Queue With


Circular Array

Queues

54

Implementing Queue With


Circular Array

Queues

55

Implementing Queue With


Circular Array

Queues

56

The Bounded queue

qback

qfro nt

qback

qback

A
C

qfro nt
I n s e r t e l e m e n t s A ,B , C R e m o v e e l e m e n t A

qfro nt
R e m o ve e le m e n t B
D

qback

q fro n t
q b a c k q fro n t
I n s e r t e le m e n t D , I n s e r t e le m e n t E

qback

qback

qfro nt
In s e r t e le m e n t D ,
D

q fro n t C
q fro n t C
qback
I n s e r t e le m e n t D , I n s e r t e le m e n t E

A r r a y V ie w

C ir c u la r V ie w
Queues

57

Methods to Implement

i = (( i + 1) == max) ? 0 : (i + 1);

if (( i + 1) == max) i = 0; else i = i + 1;

i = ( i + 1) % max;

Queues

58

Queue Operations

We use the
modulo operator
(remainder of
division)

Algorithm size()
return (N f + r) mod N
Algorithm isEmpty()
return (f r)

Q
0 1 2

0 1 2

Q
f
Queues

59

Queue Operations (cont.)

Operation enqueue throws


an exception if the array is
full
This exception is
implementation-dependent

Algorithm enqueue(o)
if size() = N 1 then
throw FullQueueException
else
Q[r] o
r (r + 1) mod N

Q
0 1 2

0 1 2

Q
f
Queues

60

Queue Operations (cont.)

Operation dequeue
throws an exception if
the queue is empty
This exception is
specified in the queue
ADT

Algorithm dequeue()
if isEmpty() then
throw EmptyQueueException
else
o Q[f]
f (f + 1) mod N
return o

Q
0 1 2

0 1 2

Q
f
Queues

61

Boundary Conditions

Queues

62

Implementation
The physical model: a linear array with the front
Considerations

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

63

Growable Array-based Queue

In an enqueue operation, when the array is


full, instead of throwing an exception, we can
replace the array with a larger one
Similar to what we did for an array-based
stack
The enqueue operation has amortized running
time

O(n) with the incremental strategy


O(1) with the doubling strategy

Queues

64

Implementing a Queue

Linked List based

Where is front? Where is back?


How are elements added, removed?

Efficiency of operations

Queues

65

Queue with a Singly Linked


List

We can implement a queue with a singly linked list


The front element is stored at the first node
The rear element is stored at the last node
The space used is O(n) and each operation of the Queue
ADT takes O(1) time

nodes

Queues

elements

66

Implementing Queue: SinglyLinked List


This requires front and rear Node pointers:
template<typename Item_Type>
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

67

Using a Single-Linked List to


Implement a Queue
(continued)

Queues

68

Implementing Queue: SinglyLinked List

Insert at tail, using back_of_queue for speed


Remove using front_of_queue
Adjust size when adding/removing

No need to iterate through to determine size

Queues

69

Analysis of the Space/Time


Issues

Time efficiency of singly- or doubly-linked list good:


O(1) for all Queue operations

Space cost: ~3 extra words per item

vector uses 1 word per item when fully packed


2 words per item when just grown
On average ~1.5 words per item, for larger lists

Queues

70

Comparing the Three


Implementations

All three are comparable in time: O(1) operations


Linked-lists require more storage

Singly-linked list: ~3 extra words / element


Doubly-linked list: ~4 extra words / element

Circular array: 0-1 extra word / element

On average, ~0.5 extra word / element

Queues

71

Analysis of the Space/Time


Issues

vector Implementation

Insertion at end of vector is O(1), on average


Removal 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

72

Queues

73

Queues

74

THE deque CLASS IS VERY SIMILAR TO


THE vector CLASS.

Queues

75

The deque

The 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

76

The deque class

Queues

77

The deque class (2)

Queues

78

The deque class (3)

Queues

79

Queues

80

THE deque CLASS ALSO HAS ALL OF


THE METHODS FROM THE vector CLASS
(EXCEPT FOR capacity AND reserve),
AND THE INTERFACES ARE THE SAME!

Queues

81

deque<string>words;
string word;

Whats output?

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 << words [i] << endl;

Queues

82

ON PAPER, THAT IS, LOOKING AT BIGO TIME ESTIMATES ONLY, A DEQUE IS


SOMETIMES FASTER AND NEVER
SLOWER THAN A VECTOR.

Queues

83

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.

Queues

84

The Standard Library


Implementation

The 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

85

The Standard Library


Implementation (2)

Queues

86

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

87

map

start

yes
true

now
good

right

love
clear
finish

Queues

88

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

89

DEQUE ITERATORS ARE GENIUSES!

Queues

90

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

91

map

start

yes
true
now
good

right

love
clear
finish

Queues

92

SUPPOSE THE DEQUE SHOWN IN THE


PREVIOUS SLIDE IS words. HOW DOES
RANDOM ACCESS WORK? FOR
EXAMPLE, HOW IS words [5]
ACCESSED?

Queues

93

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

94

THE ITEM AT words [5], AT AN OFFSET


OF 3 FROM THE START OF BLOCK 1, IS
clear.

Queues

95

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

96

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

97

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.

Queues

98

Priority Queue

A Special form of queue from which items are


removed according to their designated priority and
not the order in which they entered.
Job # 1
M an ager

Job # 4
S u p e r v is o r

Job # 3
C le r k

Job # 2
P r e s id e n t

Items entered the queue in sequential order but will be


removed in the order #2, #1, #4, #3.
Queues

99

CLASS priority_queue

Constructor

<queue>

priority_queue();
Create an empty priority queue. Type T must
implement the operator <.
CLASS priority_queue

Operations

<queue>

bool empty() const;


Check whether the priority queue is empty. Return true
if it is empty, and false otherwise. Create
void pop();
Remove the item of highest priority from the queue.
Precondition: The priority queue is not empty.
Postcondition: The priority queue has 1 less element
Queues

100

CLASS priority_queue

Operations

<queue>

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

101

PQ Implementation

How would you implement a priority queue?

Queues

102

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

103 10

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

104 10

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

105 10

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

106 10

You might also like