Queues - PowerPoint PPT Presentation

1 / 106
About This Presentation
Title:

Queues

Description:

Simulation allows designers to estimate performance. Before ... Use an array of size N in a circular fashion. Two variables keep track of the front and rear ... – PowerPoint PPT presentation

Number of Views:71
Avg rating:3.0/5.0
Slides: 107
Provided by: cseS2
Category:
Tags: queues

less

Transcript and Presenter's Notes

Title: Queues


1
Queues
  • Briana B. Morrison
  • Adapted from Alan Eugenio

2
Topics
  • Define Queue
  • APIs
  • Applications
  • Radix Sort
  • Simulation
  • Implementation
  • Array based
  • Circular
  • Empty, one value, full
  • Linked list based
  • Deques
  • Priority Queues

3
(No Transcript)
4
The Queue
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.
5
(No Transcript)
6
(No Transcript)
7
(No Transcript)
8
(No Transcript)
9
void push(const T item) Insert the argument
item at the back of the queue. Postcondition Th
e queue has a new item at the back
int size() const Return the number of elements
in the queue.
10
(No Transcript)
11
DETERMINE THE OUTPUT FROM THE FOLLOWING queueltin
tgt my_queue for (int i 0 i lt 10 i)
my_queue.push (i i) while (!my_queue.empty())
cout ltlt my_queue.front() ltlt endl
my_queue.pop() // while
12
(No Transcript)
13
(No Transcript)
14
deque? list? vector?
OK OK NOT OK NO pop_front METHOD
15
Implementing Queue adapter of stdlist
  • 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

16
(No Transcript)
17
(No Transcript)
18
(No Transcript)
19
(No Transcript)
20
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

21
(No Transcript)
22
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).
23
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 (101). Final Sequence 6 15 22 30 35
39 85 91 92
24
Radix Sort
  • Use an array of queues (or vector of queues) as
    the buckets
  • void radixSort (vectorltintgt v, int d)
  • int i
  • int power 1
  • queueltintgt digitQueue10
  • for (i0i lt di)
  • distribute(v, digitQueue, power)
  • collect(digitQueue, v)
  • power 10

25
  • // support function for radixSort()
  • // distribute vector elements into one of 10
    queues
  • // using the digit corresponding to power
  • // power 1 gt 1's digit
  • // power 10 gt 10's digit
  • // power 100 gt 100's digit
  • // ...
  • void distribute(const vectorltintgt v, queueltintgt
    digitQueue,
  • int power)
  • int i
  • // loop through the vector, inserting each
    element into
  • // the queue (vi / power) 10
  • for (i 0 i lt v.size() i)
  • digitQueue(vi / power) 10.push(vi)

26
  • // support function for radixSort()
  • // gather elements from the queues and copy back
    to the vector
  • void collect(queueltintgt digitQueue,
    vectorltintgt v)
  • int i 0, digit
  • // scan the vector of queues using indices 0, 1,
    2, etc.
  • for (digit 0 digit lt 10 digit)
  • // collect items until queue empty and copy
    items back
  • // to the vector
  • while (!digitQueuedigit.empty())
  • vi digitQueuedigit.front()
  • digitQueuedigit.pop()
  • i

27
(No Transcript)
28
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.
29
(No Transcript)
30
(No Transcript)
31
(No Transcript)
32
(No Transcript)
33
(No Transcript)
34
(No Transcript)
35
Simulating Waiting Lines Using Queues
  • Simulation is used to study the performance
  • Of a physical (real) system
  • By using a physical, mathematical, or computer
    model of the system
  • Simulation allows designers to estimate
    performance
  • Before building a system
  • Simulation can lead to design improvements
  • Giving better expected performance of the system

36
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

37
Simulate Strategies for Airline Check-In
38
Simulate Airline Check-In
  • We will maintain a simulated clock
  • 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)

39
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

40
Simulate Airline Check-In
  • Design approach
  • Agent data type models airline agent
  • Passenger data type models passengers
  • 2 queueltPassengergt, 1 for FF, 1 for R
  • Overall Airline_Checkin_Sim class

41
Simulate Airline Check-In
42
(No Transcript)
43
(No Transcript)
44
(No Transcript)
45
(No Transcript)
46
(No Transcript)
47
(No Transcript)
48
(No Transcript)
49
(No Transcript)
50
(No Transcript)
51
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?

52
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
wrapped-around configuration
53
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

54
Implementing Queue With Circular Array
55
Implementing Queue With Circular Array
56
Implementing Queue With Circular Array
57
The Bounded queue
58
Methods to Implement
  • i (( i 1) max) ? 0 (i 1)
  • if (( i 1) max) i 0 else i i 1
  • i ( i 1) max

59
Queue Operations
  • We use the modulo operator (remainder of division)

Algorithm size() return (N - f r) mod
N Algorithm isEmpty() return (f r)
60
Queue Operations (cont.)
Algorithm enqueue(o) if size() N ? 1
then throw FullQueueException else Qr ?
o r ? (r 1) mod N
  • Operation enqueue throws an exception if the
    array is full
  • This exception is implementation-dependent

61
Queue Operations (cont.)
Algorithm dequeue() if isEmpty() then throw
EmptyQueueException else o ? Qf f ? (f
1) mod N return o
  • Operation dequeue throws an exception if the
    queue is empty
  • This exception is specified in the queue ADT

62
Boundary Conditions
63
Implementation Considerations
  • The 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.

64
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

65
Implementing a Queue
  • Linked List based
  • Where is front? Where is back?
  • How are elements added, removed?
  • Efficiency of operations

66
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

r
nodes
f
?
elements
67
Implementing Queue Singly-Linked List
  • This requires front and rear Node pointers
  • templatelttypename Item_Typegt
  • 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

68
Using a Single-Linked List to Implement a Queue
(continued)
69
Implementing Queue Singly-Linked 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

70
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

71
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

72
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)

73
(No Transcript)
74
(No Transcript)
75
(No Transcript)
76
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.

77
The deque class
78
The deque class (2)
79
The deque class (3)
80
(No Transcript)
81
(No Transcript)
82
Whats output?
83
(No Transcript)
84
(No Transcript)
85
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.

86
The Standard Library Implementation (2)
87
(No Transcript)
88
(No Transcript)
89
(No Transcript)
90
(No Transcript)
91
(No Transcript)
92
(No Transcript)
93
(No Transcript)
94
(No Transcript)
95
(No Transcript)
96
(No Transcript)
97
(No Transcript)
98
(No Transcript)
99
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.
Items entered the queue in sequential order but
will be removed in the order 2, 1, 4, 3.
100
(No Transcript)
101
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().
102
PQ Implementation
  • How would you implement a priority queue?

103
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.
103
104
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.
104
105
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.
105
106
Summary Slide 4
- Priority queue - Pop() returns the highest
priority item (largest or smallest). - Norma
lly implemented by a heap, which is
discussed later in the class. - The
push() and pop() operations have running time
O(log2n)
106
Write a Comment
User Comments (0)
About PowerShow.com