Top Banner

of 106

Queues 2

Jun 04, 2018

Download

Documents

Prashant Jain
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 8/14/2019 Queues 2

    1/106

    Queues

    Briana B. Morrison

    Adapted from Alan Eugenio

  • 8/14/2019 Queues 2

    2/106

    Queues 2

    Topics Define Queue

    APIs

    Applications Radix Sort

    Simulation

    Implementation Array based

    Circular

    Empty, one value, full

    Linked list based Deques

    Priority Queues

  • 8/14/2019 Queues 2

    3/106

    Queues 3

    A QUEUEIS A CONTAINER IN WHICH:

    . INSERTIONS ARE MADE ONLY AT

    THE BACK;

    . DELETIONS, RETRIEVALS, AND

    MODIFICATIONS ARE MADE ONLY

    AT THE FRONT.

  • 8/14/2019 Queues 2

    4/106

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

    C

    B C

    A B C

    A

    backfront

    push A

    A Bfront back

    push B

    front back push C

    front back

    pop A

    frontback

    pop B

  • 8/14/2019 Queues 2

    5/106

    Queues 5

    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 ITEMINSERTED WILL BE THE FIRST ITEM

    DELETED: FIFO (FIRST-IN, FIRST-OUT)

  • 8/14/2019 Queues 2

    6/106

    Queues 6

    METHOD INTERFACES

    FOR THE

    queueCLASS

  • 8/14/2019 Queues 2

    7/106

    Queues 7

    CLASS queue Constructor

    queue();

    Create an empty queue.

    CLASS queue Operations

    boolempty() const;

    Check whether the queue is empty. Return true if it isempty 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.

  • 8/14/2019 Queues 2

    8/106

    Queues 8

    CLASS queue Operations

    const T&front() const;

    Constant version of front().

    voidpop();

    Remove the item from the front of the queue.

    Precondition: The queue is not empty.

    Postcondition: The element at the front of the queueis the element that was addedimmediately after the element justpopped or the queue is empty.

  • 8/14/2019 Queues 2

    9/106

    Queues 9

    CLASS queue Operations

    voidpush(const T& item);

    Insert the argument item at the back of the queue.

    Postcondition: The queue has a new item at the back

    intsize() const;

    Return the number of elements in the queue.

  • 8/14/2019 Queues 2

    10/106

    Queues 10

    THERE ARE NO ITERATORS!

    THE ONLY ACCESSIBLE ITEM IS THEFRONT ITEM.

  • 8/14/2019 Queues 2

    11/106

    Queues 11

    DETERMINE THE OUTPUT FROM THE

    FOLLOWING:

    queue my_queue;

    for(inti = 0; i < 10; i++)

    my_queue.push (i * i);

    while(!my_queue.empty())

    {cout

  • 8/14/2019 Queues 2

    12/106

    Queues 12

    THE queueCLASS IS TEMPLATED:

    template

    TIS THE TEMPLATE PARAMETER

    FOR THE ITEM TYPE. ContainerIS THE

    TEMPLATE PARAMETER FOR THE

    CLASS THAT WILL HOLD THE ITEMS,

    WITH THE dequeCLASS THE DEFAULT.

  • 8/14/2019 Queues 2

    13/106

    Queues 13

    THE queueCLASS IS A CONTAINER

    ADAPTOR. A CONTAINER ADAPTORC

    CALLS THE METHODS FROM SOME

    OTHER CLASS TO DEFINE THE

    METHODS IN C.

  • 8/14/2019 Queues 2

    14/106

    Queues 14

    SPECIFICALLY, THE queueCLASS

    ADAPTS ANY CONTAINER CLASS

    THAT HAS push_back, pop_front, front,

    size, AND emptyMETHODS.

    deque?

    list?

    vector?

    OK

    OK

    NOT OK: NO pop_frontMETHOD

  • 8/14/2019 Queues 2

    15/106

    Queues 15

    Implementing Queue: adapter of std::list

    This is a simple adapter class, with following mappings:

    Queuepushmaps topush_back

    Queue frontmaps front

    Queuepop

    maps topop_front

    ...

    This is the approach taken by the C++ standard library.

    Any sequential container that supportspush_back,

    front, andpop_frontcan be used. The list

    The deque

  • 8/14/2019 Queues 2

    16/106

    Queues 16

    THE STANDARD C++ REQUIRES THAT

    THE DEFINITION OF THE queueCLASS INCLUDE

    protected:Container c;

  • 8/14/2019 Queues 2

    17/106

    Queues 17

    ALSO, THE METHOD DEFINITIONS

    ARE PRESCRIBED. FOR EXAMPLE,

    public:

    voidpush (constvalue_type& x) { c.push_back (x)); }

    voidpop( ) { c.pop_front( ); }

    constT& front( ) const { returnc.front( ); }

  • 8/14/2019 Queues 2

    18/106

    Queues 18

    miniQ.push(10)

    miniQ.push(25)

    miniQ.push(50)

    n = miniQ.front() // n = 10

    miniQ.pop()

    Queue Statement ListList StatementQueue

    10

    backfrontqlist.push_back(10)

    10

    backfront

    10 25

    backfront

    qlist.push_back(25) 10 25

    backfront

    5010 25

    backfront

    qlist.push_back(50)10 25

    front

    50

    back

    return qlist.front() // return 10

    25 50

    backfront

    qlist.pop_front() 25 50

    miniQueue miniQ; // declare an empty queue

  • 8/14/2019 Queues 2

    19/106

    Queues 19

    IF EITHER A DEQUE OR LIST IS THE

    UNDERLYING CONTAINER,

    worstTime(n) IS CONSTANT FOR EACH

    METHOD.

    EXCEPTION: FOR THE pushMETHOD,IF A DEQUE IS THE UNDERLYING

    CONTAINER, worstTime(n) IS LINEAR IN

    n, AND averageTime(n) IS CONSTANT

    (AND amortizedTime(n) IS CONSTANT).

  • 8/14/2019 Queues 2

    20/106

    Queues 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

  • 8/14/2019 Queues 2

    21/106

    Queues 21

    APPLICATION OF QUEUES:

    RADIX SORT

  • 8/14/2019 Queues 2

    22/106

    Queues 22

    The Radix SortOrder ten 2 digit numbers in 10 bins from smallestnumber to largest number. Requires 2 calls to the sortAlgorithm.

    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

    ).

    9130

    0

    39

    987

    6

    6

    3515

    85

    543

    22

    92

    21

  • 8/14/2019 Queues 2

    23/106

    Queues 23

    The Radix SortAfter Collection: 30 91 92 22 85 15 35 6 39

    Pass 1: Take the new sequence and distribute thecards into bins determined by the 10's digit (101).

    Final Sequence: 6 15 22 30 35 39 85 91 92

    6

    0

    9291

    9

    85

    87654

    39

    3530

    3

    22

    2

    15

    1

  • 8/14/2019 Queues 2

    24/106

    Queues 24

    Radix Sort Use an array of queues (or vector of queues) as the buckets

    void 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;

    }

    }

  • 8/14/2019 Queues 2

    25/106

    Queues 25

    // 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]);

    }

  • 8/14/2019 Queues 2

    26/106

    Queues 26

    // support function for radixSort()

    // gather elements from the queues and copy back to the vector

    void 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 vector

    while (!digitQueue[digit].empty())

    {

    v[i] = digitQueue[digit].front();

    digitQueue[digit].pop();

    i++;

    }

    }

  • 8/14/2019 Queues 2

    27/106

    Queues 27

    APPLICATION OF QUEUES:

    COMPUTER SIMULATION

  • 8/14/2019 Queues 2

    28/106

  • 8/14/2019 Queues 2

    29/106

    Queues 29

    PHYSICAL MODEL : DIFFERS FROM

    THE SYSTEM ONLY IN SCALE ORINTENSITY.

    EXAMPLES: WAR GAMES, PRE-SEASON

  • 8/14/2019 Queues 2

    30/106

    Queues 30

    MATHEMATICAL MODEL : A SET OF

    EQUATIONS, VARIABLES, ANDASSUMPTIONS

  • 8/14/2019 Queues 2

    31/106

    Queues 31

    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?

  • 8/14/2019 Queues 2

    32/106

    Queues 32

    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

  • 8/14/2019 Queues 2

    33/106

    Queues 33

    DEVELOPSystem Computer

    Model

    VERIFY RUN

    Interpretation Output DECIPHER

  • 8/14/2019 Queues 2

    34/106

    Queues 34

    IF THE INTERPRETATION DOES NOT

    CORRESPOND TO THE BEHAVIOR OF

    THE SYSTEM, CHANGE THE MODEL!

  • 8/14/2019 Queues 2

    35/106

    Queues 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

    Beforebuilding a system Simulation can lead to design improvements

    Giving betterexpected performance of the system

  • 8/14/2019 Queues 2

    36/106

    Queues 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 realsystems

    Airline check-in counter, for example

    Special branch of mathematics for these problems:Queuing Theory

  • 8/14/2019 Queues 2

    37/106

    Queues 37

    Simulate Strategies for Airline Check-In

  • 8/14/2019 Queues 2

    38/106

    Queues 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:

    1.

    Frequent flyer (FF) passenger arrives in line2. Regular (R) passenger arrives in line

    3. Agent finishes, then serves next FFpassenger

    4. Agent finishes, then serves next Rpassenger

    5. Agent is idle (both lines empty)

  • 8/14/2019 Queues 2

    39/106

    Queues 39

    Simulate Airline Check-In

    Simulation uses someparameters:

    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

  • 8/14/2019 Queues 2

    40/106

    Queues 40

    Simulate Airline Check-In

    Design approach:

    Agentdata type models airline agent

    Passengerdata type models passengers

    2 queue, 1 for FF, 1 for R OverallAirline_Checkin_Simclass

  • 8/14/2019 Queues 2

    41/106

    Queues 41

    Simulate Airline Check-In

  • 8/14/2019 Queues 2

    42/106

    Queues 42

    QUEUE APPLICATION

    A SIMULATED CAR WASH

  • 8/14/2019 Queues 2

    43/106

    Queues 43

    PROBLEM:

    GIVEN THE ARRIVAL TIMES AT

    SPEEDYS CAR WASH, CALCULATE THE

    AVERAGE WAITING TIME PER CAR.

  • 8/14/2019 Queues 2

    44/106

    Queues 44

    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

  • 8/14/2019 Queues 2

    45/106

    Queues 45

    AVERAGE WAITING TIME = SUM OF

    WAITING TIMES / NUMBER OF CARS

    IN A GIVEN MINUTE, A DEPARTURE IS

    PROCESSED BEFORE AN ARRIVAL.

  • 8/14/2019 Queues 2

    46/106

    Queues 46

    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.

  • 8/14/2019 Queues 2

    47/106

    Queues 47

    SYSTEM TEST 1:8

    111113

    14161620

    999

    TIME EVENT WAITING TIME

  • 8/14/2019 Queues 2

    48/106

    Queues 48

    TIME EVENT WAITING TIME8 ARRIVAL11 ARRIVAL11 ARRIVAL13 ARRIVAL14 ARRIVAL16 ARRIVAL16 ARRIVAL (OVERFLOW)

    18 DEPARTURE 020 ARRIVAL28 DEPARTURE 7

    38 DEPARTURE 1748 DEPARTURE 2558 DEPARTURE 3468 DEPARTURE 42

    78 DEPARTURE 48

  • 8/14/2019 Queues 2

    49/106

    Queues 49

    AVERAGE WAITING TIME

    = 173 / 7.0 MINUTES

    = 24.7 MINUTES

  • 8/14/2019 Queues 2

    50/106

    Queues 50

    CAR WASH APPLET

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

  • 8/14/2019 Queues 2

    51/106

    Queues 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?

  • 8/14/2019 Queues 2

    52/106

    Queues 52

    Array-based Queue

    Use an array of size Nin 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 ris kept empty

    Q0 1 2 rf

    normal configuration

    Q0 1 2 fr

    wrapped-around configuration

  • 8/14/2019 Queues 2

    53/106

    Queues 53

    Implementing queueWith 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 rearKey innovation:

    If you hit the end of the array wrap aroundto slot 0

    This prevents our needing to shift elements around

    Still have to deal with overflow of space

  • 8/14/2019 Queues 2

    54/106

    Queues 54

    Implementing Queue With Circular Array

    l Q h l A

  • 8/14/2019 Queues 2

    55/106

    Queues 55

    Implementing Queue With Circular Array

  • 8/14/2019 Queues 2

    56/106

    Th d d

  • 8/14/2019 Queues 2

    57/106

    Queues 57

    The Bounded queue

    A

    BC

    qfrontqback

    Insert elements A,B, C

    BC qfront

    qback

    Remove element A

    D

    C

    qfront

    qback

    Insert element D,

    Cqfront

    qback

    Remove element B

    D

    Cqfront

    qback

    Insert element D,

    Cqfront qback

    Insert element E

    Circular ViewArray View

    D E

    Insert element D, Insert element E

    C D

    qfrontqback

    E C D

    qfrontqback

    h d l

  • 8/14/2019 Queues 2

    58/106

    Queues 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;

    Q O i

  • 8/14/2019 Queues 2

    59/106

    Queues 59

    Queue Operations

    We use the

    modulo operator

    (remainder of

    division)

    Algorithmsize()

    return(N-f+r) mod N

    AlgorithmisEmpty()

    return(f=r)

    Q0 1 2 r

    f

    Q0 1 2 fr

    Q O i ( )

  • 8/14/2019 Queues 2

    60/106

    Queues 60

    Queue Operations (cont.)

    Algorithmenqueue(o)

    ifsize()=N-1then

    throw FullQueueException

    else

    Q[r] or(r + 1) mod N

    Operation enqueue throwsan exception if the array isfull

    This exception isimplementation-dependent

    Q0 1 2 r

    f

    Q0 1 2 fr

    Q O i ( )

  • 8/14/2019 Queues 2

    61/106

    Queues 61

    Queue Operations (cont.)

    Operation dequeuethrows an exception ifthe queue is empty

    This exception isspecified in the queue

    ADT

    Algorithmdequeue()

    ifisEmpty()then

    throw EmptyQueueException

    else

    oQ[f]f(f + 1) mod N

    returno

    Q0 1 2 rfQ

    0 1 2 fr

    B d C di i

  • 8/14/2019 Queues 2

    62/106

    Queues 62

    Boundary Conditions

    I l i C id i

  • 8/14/2019 Queues 2

    63/106

    Queues 63

    Implementation Considerations Thephysical model: a linear array with the front

    always in the first position and all entries moved upthe 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.

    G bl A b d Q

  • 8/14/2019 Queues 2

    64/106

    Queues 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-basedstack

    The enqueue operation has amortized running

    time

    O(n)with the incremental strategy O(1)with the doubling strategy

    I l i Q

  • 8/14/2019 Queues 2

    65/106

    Queues 65

    Implementing a Queue

    Linked List based

    Where is front? Where is back?

    How are elements added, removed?

    Efficiency of operations

    Q i h Si l Li k d Li

  • 8/14/2019 Queues 2

    66/106

    Queues 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

    f

    r

    nodes

    elements

    I l ti Q Si l Li k d Li t

  • 8/14/2019 Queues 2

    67/106

    Queues 67

    Implementing Queue: Singly-Linked List

    This requires frontand rearNodepointers:

    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;

    };

    U i Si l Li k d Li t t

  • 8/14/2019 Queues 2

    68/106

    Queues 68

    Using a Single-Linked List to

    Implement a Queue (continued)

    Impl m ti Q Si l Li k d Li t

  • 8/14/2019 Queues 2

    69/106

    Queues 69

    Implementing Queue: Singly-Linked List

    Insert at tail, usingback_of_queuefor speed

    Remove using front_of_queue

    Adjust sizewhen adding/removing

    No need to iterate through to determine size

    A l i f th Sp /Ti I

  • 8/14/2019 Queues 2

    70/106

    Queues 70

    Analysis of the Space/Time Issues

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

    O(1) for all Queueoperations

    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

    Comparing the Three Implementations

  • 8/14/2019 Queues 2

    71/106

    Queues 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

    Anal sis of the Space/Time Iss es

  • 8/14/2019 Queues 2

    72/106

    Queues 72

    Analysis of the Space/Time Issues

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

  • 8/14/2019 Queues 2

    73/106

    A DEQUE IS A FINITE SEQUENCE OF

  • 8/14/2019 Queues 2

    74/106

    Queues 74

    A DEQUEIS A FINITE SEQUENCE OF

    ITEMS SUCH THAT

    1.GIVEN ANY INDEX, THE ITEM INTHE SEQUENCE AT THAT INDEXCAN BE ACCESSED OR MODIFIEDIN CONSTANT TIME.

    2.AN INSERTION OR DELETION AT

    THE FRONTOR BACK OF THESEQUENCE TAKES ONLYCONSTANT TIME, ON AVERAGE.

  • 8/14/2019 Queues 2

    75/106

    Queues 75

    THE dequeCLASS IS VERY SIMILAR TO

    THE vectorCLASS.

    The deque

  • 8/14/2019 Queues 2

    76/106

    Queues 76

    The deque

    The deque is an abstract data type thatcombines the features of a stack and a

    queue.

    The name deque is an abbreviation fordouble-ended queue.

    The C++ standard defines the deque as a

    full-fledged sequential container that supportsrandom access.

    The deque class

  • 8/14/2019 Queues 2

    77/106

    Queues 77

    The deque class

    Member Function Behaviorconst Item_Type&

    operator[](size_t index)const;

    Item_Type&

    operator[](size_t index)

    Returns a reference to the element at positionindex.

    const Item_Type&

    at(size_t index) const;

    Item_Type&

    at(size_t index)

    Returns a reference to the element at positionindex. If indexis not valid, theout_of_rangeexception is thrown.

    iterator insert(iterator pos,

    const Item_Type& item)

    Inserts a copy of iteminto the dequeatposition pos. Returns an iteratorthatreferences the newly inserted item.

    iterator erase(iterator pos) Removes the item from the dequeat

    position pos. Returns an iteratorthatreferences the item following the one erased.

    void remove(const Item_Type&

    item)

    Removes all occurrences of itemfrom thedeque.

    The deque class (2)

  • 8/14/2019 Queues 2

    78/106

    Queues 78

    The deque class (2)

    Member Function Behaviorvoid push_front(const Item_Type&

    item)

    Inserts a copy of itemas the first element ofthe deque

    void push_back(const Item_Type&

    item)

    Inserts a copy of itemas the last element ofthe 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 thedeque.

    Item_Type& back();

    const Item_Type& back() const

    Returns a reference to the last item in thedeque.

    iterator begin() Returns an iteratorthat references thefirst item of the deque.

    const_iterator begin() const Returns a const_iteratorthat referencesthe first item of the deque.

    The deque class (3)

  • 8/14/2019 Queues 2

    79/106

    Queues 79

    The deque class (3)

    Member Function Behavioriterator end() Returns an iteratorthat references one

    past the last item of the deque.

    const_iterator end() const Returns a const_iteratorthat referencesone past the last item of the deque.

    void swap(deque

  • 8/14/2019 Queues 2

    80/106

    Queues 80

    TO TAKE ADVANTAGE OF INSERTIONSAND DELETIONS AT THE FRONT OF ADEQUE, 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.voidpush_front (constT& x);

    // Postcondition: The item at the front of this deque has// been deleted.voidpop_front( );

    THE deque CLASS ALSO HAS ALL OF

  • 8/14/2019 Queues 2

    81/106

    Queues 81

    THE dequeCLASS ALSO HAS ALL OF

    THE METHODS FROM THE vectorCLASS

    (EXCEPT FOR capacityAND reserve),

    AND THE INTERFACES ARE THE SAME!

    deq e ords

  • 8/14/2019 Queues 2

    82/106

    Queues 82

    dequewords; string word;

    for(inti = 0; i < 5; i++) { cin >> word; words.push_back (word);

    } // for words.pop_front( ); words.pop_back( ); for(unsignedi = 0; i < words.size(); i++)

    cout

  • 8/14/2019 Queues 2

    83/106

    Queues 83

    ON PAPER, THAT IS, LOOKING AT BIG-

    O TIME ESTIMATES ONLY, A DEQUE IS

    SOMETIMES FASTER AND NEVER

    SLOWER THAN A VECTOR.

  • 8/14/2019 Queues 2

    84/106

    The Standard Library Implementation

  • 8/14/2019 Queues 2

    85/106

    Queues 85

    The Standard Library Implementation

    The standard library uses a randomlyaccessible circular array.

    Each item in the circular array points to a

    fixed size, dynamically allocated array thatcontains 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.

    The Standard Library Implementation (2)

  • 8/14/2019 Queues 2

    86/106

    Queues 86

    The Standard Library Implementation (2)

    IN THE HEWLETT-PACKARD DESIGN

  • 8/14/2019 Queues 2

    87/106

    Queues 87

    IN THE HEWLETT PACKARD DESIGN

    AND IMPLEMENTATION OF THE deque

    CLASS, THERE IS A mapFIELD: A

    POINTER TO AN ARRAY. THE ARRAY

    ITSELF CONTAINS POINTERS TOBLOCKS THAT HOLD THE ITEMS. THE

    startAND finishFIELDS ARE

    ITERATORS.

    map start

  • 8/14/2019 Queues 2

    88/106

    Queues 88

    finish

    yes

    true now

    good

    loveclear

    right

    FOR CONTAINER CLASSES IN

  • 8/14/2019 Queues 2

    89/106

    Queues 89

    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.

  • 8/14/2019 Queues 2

    90/106

    Queues 90

    DEQUE ITERATORS ARE GENIUSES!

    THE iterator CLASS EMBEDDED IN THE

  • 8/14/2019 Queues 2

    91/106

    Queues 91

    THE iteratorCLASS EMBEDDED IN THEdequeCLASS HAS FOUR FIELDS:

    1.first, A POINTER TO THEBEGINNING 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 THELOCATION IN THE MAP ARRAYTHAT POINTS TO THE BLOCK.

    map start

  • 8/14/2019 Queues 2

    92/106

    Queues 92

    finish

    yes

    true

    now

    good

    love

    clearright

    SUPPOSE THE DEQUE SHOWN IN THE

  • 8/14/2019 Queues 2

    93/106

    Queues 93

    SUPPOSE THE DEQUE SHOWN IN THE

    PREVIOUS SLIDE IS words. HOW DOESRANDOM ACCESS WORK? FOR

    EXAMPLE, HOW IS words [5]

    ACCESSED?

    1.BLOCK NUMBER

  • 8/14/2019 Queues 2

    94/106

    Queues 94

    = (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

    THE ITEM AT words [5] AT AN OFFSET

  • 8/14/2019 Queues 2

    95/106

    Queues 95

    THE ITEM AT words [5], AT AN OFFSET

    OF 3 FROM THE START OF BLOCK 1, ISclear.

    FOR AN INSERTION OR REMOVAL AT

  • 8/14/2019 Queues 2

    96/106

    Queues 96

    FOR AN INSERTION OR REMOVAL AT

    SOME INDEX iIN THE INTERIOR OF A

    DEQUE, THE NUMBER OF ITEMS

    MOVED IS THE MINIMUM OF iAND

    length i. THE lengthFIELD CONTAINS

    THE NUMBER OF ITEMS.

    FOR EXAMPLE TO INSERT AT words [5]

  • 8/14/2019 Queues 2

    97/106

    Queues 97

    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.

    EXERCISE: SUPPOSE FOR SOME deque

  • 8/14/2019 Queues 2

    98/106

    Queues 98

    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 Queue

  • 8/14/2019 Queues 2

    99/106

    Queues 99

    y Q

    Job # 3

    Clerk

    Job # 4

    Supervisor

    Job # 2

    President

    Job # 1

    Manager

    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.

    CLASS priority_queue Constructor

    i it ()

  • 8/14/2019 Queues 2

    100/106

    Queues 100

    priority_queue();

    Create an empty priority queue. Type T must

    implement the operator

  • 8/14/2019 Queues 2

    101/106

    Queues 101

    voidpush(const T& item);

    Insert the argument item into the priority queue.

    Postcondition: The priority queue contains a newelement.

    intsize() const;

    Return the number of items in the priority queue.

    T&top();

    Return a reference to the item having the highestpriority.

    Precondition: The priority queue is not empty.const T&top();

    Constant version of top().

    PQ Implementation

  • 8/14/2019 Queues 2

    102/106

    Queues 102

    Q p

    How would you implement a priority queue?

    Summary Slide 1

  • 8/14/2019 Queues 2

    103/106

    Queues 103

    10

    3

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

    Summary Slide 2

  • 8/14/2019 Queues 2

    104/106

    Queues 104

    10

    4

    y- 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) sortingalgorithms are preferable in most cases.

    Summary Slide 3

  • 8/14/2019 Queues 2

    105/106

    Queues 105

    10

    5

    y- 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 withno wasted space in the array.

    Summary Slide 4

  • 8/14/2019 Queues 2

    106/106

    y- Priority queue

    - Pop() returns the highest priority item (largest orsmallest).

    - Normally implemented by a heap, which isdiscussed later in the class.

    - The push() and pop() operations have runningtime O(log2n)