cs105 queues

Upload: nagara-akuma

Post on 04-Jun-2018

233 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/13/2019 CS105 Queues

    1/47

    ADT queue: Applications andImplementations

    COMPSCI 105 C S1Recommended reading: Chapter 8 of the textbook

    Based on the lecture notes of F.M.Carrano and J.J.Prichard

  • 8/13/2019 CS105 Queues

    2/47

    COMPSCI 1052

    Can you think of other examples of queues?

    What is a Queue?

    ADT Queue

  • 8/13/2019 CS105 Queues

    3/47

    COMPSCI 1053

    The Abstract Data Type Queue

    ! Queues are appropriate for many real-world situations! Example: A line to buy a movie ticket! Computer applications, e.g. a request to print a document

    ! Simulation to see how to reduce the wait involved in an application! A queue

    ! New items enter at the back, or rear, of the queue! Items leave from the frontof the queue! First-in, first-out (FIFO) property:

    ! The first item inserted into a queue is the first item to leave

    ADT Queue

  • 8/13/2019 CS105 Queues

    4/47

    COMPSCI 1054

    The Abstract Data Type Queue

    ! ADT queueoperations (with their pseudocodes)! Create an empty queue:

    createQueue()

    ! Determine whether a queue is empty:isEmpty()

    ! Add a new item to the queue:enqueue( newItem ) throwsQueueException// Adds newItem at the back of a queue. Throws

    // QueueException if the operation is unsuccessful

    ADT Queue

  • 8/13/2019 CS105 Queues

    5/47

    COMPSCI 1055

    The Abstract Data Type Queue

    ! ADT queue operations (with their pseudocodes)! Remove from the queue the item that was added earliest:

    dequeue() throwsQueueException

    // Retrieves and removes the front of a queue.

    // Throws QueueException if the operation is// unsuccessful

    ! Remove all the items from the queue:dequeueAll()

    ! Retrieve from the queue the item that was added earliest:peek() throwsQueueException

    // Retrieves the front of a queue. Throws

    // QueueException if the retrieval is unsuccessfulADT Queue

  • 8/13/2019 CS105 Queues

    6/47

    COMPSCI 1056

    Queues implement the FIFO (first-in first-out) policy:e.g. the printer / job queue!

    enqueue( o )

    createQueue()isEmpty()

    peek()

    dequeue()

    dequeueAll()

    More formally

    ADT Queue

  • 8/13/2019 CS105 Queues

    7/47

    COMPSCI 1057

    An abstract mechanism to support simultaneous implementations:public interface QueueInterface{

    public boolean isEmpty();// Determines whether a queue is empty

    public void enqueue( Object newItem ) throwsQueueException;

    // Adds an item at the back of a queue

    public Object dequeue() throws QueueException;// Retrieves and removes the front of a queue

    public void dequeueAll();// Removes all items of a queue

    public Objectpeek() throws QueueException;// Retrieves the item at the front of a queue

    }

    Queue ADT Interface

    ADT Queue

  • 8/13/2019 CS105 Queues

    8/47

    COMPSCI 1058

    QueueInterface q = new Queue();

    q.enqueue (a);

    q.enqueue (b);

    q.enqueue (c);

    d = q.peek();

    q.dequeue();

    q.enqueue(e);

    q.dequeue();

    q

    front back

    a b c e

    d

    Sample Code

    ADT Queue

  • 8/13/2019 CS105 Queues

    9/47

    COMPSCI 1059

    The Abstract Data Type Queue

    Fig. 8-2

    ADT Queue

  • 8/13/2019 CS105 Queues

    10/47

    COMPSCI 10510

    Applications! Print queue! Reading a string of characters

    ! A queue can retain characters in the order in which they are typedqueue.createQueue()

    while ( not end of line) {

    read a new characterch

    queue.enqueue( ch )

    }

    ! Once the characters are in a queue, the system can process them asnecessary

    ! Level order traversal of trees! Checking palindrome: e.g. Mac spots tip at a pit-stop scam

    ! To enjoy palindromes, see http://thinks.com/words/palindromesADT Queue

  • 8/13/2019 CS105 Queues

    11/47

    COMPSCI 10511

    ! Reading a sequence of digits separated by space into a queuewhile(chis not blank andchis a digit) {

    queue.enqueue( ch)}

    ! Convert digits in queue into a decimal integer nn= 0;while ( !queue.isEmpty() ) {

    ch= queue.dequeue();n= 10 n + integer thatch represents

    }

    Convert digits into decimal integer

    ADT Queue

  • 8/13/2019 CS105 Queues

    12/47

    Convert digits into decimal integer

    ! An example: a sequence 61835read into the queue:! 5 3 8 1 6

    ! Conversion:! n= 0! n= 0 * 10 + 6 = 6! n= 6 * 10 + 1 = 61! n= 61 * 10 + 8 = 618! n= 618 * 10 + 3 = 6183! n= 6183 * 10 + 5 = 61835! Terminate and return n: queue is empty

    COMPSCI 10512 ADT Queue

  • 8/13/2019 CS105 Queues

    13/47

    COMPSCI 10513

    Recognizing Palindrome

    ! A string which reads the same either left to right, or right toleftis known as a palindrome

    ! Palindromes: r a d a r and d e e d! Counter Example: d a t a

    Procedure for a given string: Stackto reverse the character

    order of string

    Queueto preserve the characterorder of string

    Check if the two sequences arethe same

    ADT Queue

  • 8/13/2019 CS105 Queues

    14/47

    COMPSCI 10514

    public static booleanpalindrome ( String str)

    throws Exception {StackInterfaces = new Stack();QueueInterfaceq = new Queue();

    // push string into stack, and also queue

    for ( int j = 0; j

  • 8/13/2019 CS105 Queues

    15/47

    COMPSCI 10515

    Implementations of Queues

    Either an array-basedor a reference-based implementation

    Reference-based

    implementation:

    (a) Linear linked list with

    two external

    references to thefront and to the back

    (b) Circular linked list

    with one external

    reference to the back

    Fig. 8-4

    ADT Queue

  • 8/13/2019 CS105 Queues

    16/47

    COMPSCI 10516

    Inserting an item into a non-empty queue

    1. Change the nextreference in the new node to the front of the queue2. Change the nextreference in the back node to the new node3. Change the external reference lastNodeto the new node

    lastNode newNode

    (references new node)

    Fig. 8-5

    Reference-Based Implementation

    ADT Queue

  • 8/13/2019 CS105 Queues

    17/47

    COMPSCI 10517

    ! Inserting an item into an empty queue! Change the nextreference in the new node to itself! Change the external reference lastNodeto the new node

    Fig. 8-6: (a) before insertion; (b) after insertion

    Reference-Based Implementation

    ADT Queue

  • 8/13/2019 CS105 Queues

    18/47

    COMPSCI 10518

    public class QueueReferenceBased

    implements QueueInterface {private NodelastNode;public QueueReferenceBased() {

    lastNode= null};public Objectdequeue() throws QueueException {

    if ( !isEmpty() ) {

    NodefirstNode=lastNode.getNext();if ( firstNode==lastNode) {lastNode= null;

    } else {lastNode.setNext( firstNode.getNext() );

    }return firstNode.getItem();

    } else {throw new QueueException (

    Queue exception on dequeue: queue empty);}

    } // end dequeue

    }

    Deleting an item from a queue of more than one item

    Reference-Based Implementation

    ADT Queue

  • 8/13/2019 CS105 Queues

    19/47

    COMPSCI 10519

    public Objectdequeue() throws QueueException {

    if ( !isEmpty() ) {NodefirstNode=lastNode.getNext();if ( firstNode==lastNode) {

    lastNode= null;} else {

    lastNode.setNext( firstNode.getNext() );}return firstNode.getItem();

    } else {throw new QueueException (

    Queue exception on dequeue: queue empty);}

    } // end dequeue Fig. 8-7

    Deleting an item from a queue of more than one item

    Reference-Based Implementation

    ADT Queue

  • 8/13/2019 CS105 Queues

    20/47

    COMPSCI 10520

    An array with frontand backpointers as implementation of queue(a) Naive array-based implementation

    (b) Rightward drift can cause the queue to appear full

    Fig. 8-8

    (a)

    (b)

    Array-Based Implementation

    ADT Queue

  • 8/13/2019 CS105 Queues

    21/47

    COMPSCI 10521

    2 4 1 730

    front back 0 1 2 3 MAX_QUEUE - 1

    items

    Fig. 8-9

    Array-Based Implementation

    Solution 1: Shifting array elements to the left after each deletion too expensive !

    Solution 2: Viewing the array as a circular structure(eliminates the problem of rightward drift)

    ADT Queue

  • 8/13/2019 CS105 Queues

    22/47

    COMPSCI 10522

    Array-Based Implementation!

    A count of the queue items to detect queue-full and queue-emptyconditions

    ! To initialize the queue, set frontto 0,backtoMAX_QUEUE 1,and countto 0

    ! Inserting into a queue: back = ( back + 1 ) % MAX_QUEUE;items[back] = newItem;++count;

    ! Deleting from a queue: front = ( front + 1 ) % MAX_QUEUE;--count;

    ! Variations of the array-based implementation:! Use a flag fullto distinguish between the full and empty conditions! DeclareMAX_QUEUE + 1locations for the array items, but use onlyMAX_QUEUEof them for queue items

    ADT Queue

  • 8/13/2019 CS105 Queues

    23/47

    COMPSCI 10523

    ! Queue-empty: frontis one slot ahead ofback! When either frontorbackadvances pastMAX_QUEUE - 1,

    it wraps around to 0! The wrap-around effect: by using modulo arithmetic (the Java %operator)

    ! Counting queue items to detect queue-full and queue-emptyconditions

    Fig. 8-9

    e.g., insert newIteminto the queue as:

    back =

    ( back+1 ) % MAX_QUEUE;

    items[back] = newItem;

    ++count;

    How To Advance

    ADT Queue

  • 8/13/2019 CS105 Queues

    24/47

    COMPSCI 10524

    public class QueueArrayBasedimplements QueueInterface {

    private final intMAX_QUEUE= 50;

    private Object [] items;

    private intfront,back,count;

    // default constructor

    public QueueArrayBased() {

    items= new Object[MAX_QUEUE];

    front= 0;

    back=MAX_QUEUE- 1;count= 0;

    }

    Array-Based Implementation

    ADT Queue

  • 8/13/2019 CS105 Queues

    25/47

    COMPSCI 10525

    public boolean isEmpty() {return count== 0;

    }public boolean isFull() {

    return count==MAX_QUEUE;}public void enqueue( Object newItem )

    throws QueueException {if ( !isFull() ) {

    back= (back+ 1 ) %MAX_QUEUE;items[back ] = newItem ;++count;

    } else {

    throw QueueException("Queue Exception on enqueue: Queue full") ;

    }}// end enqueue

    Array-Based Implementation

    ADT Queue

  • 8/13/2019 CS105 Queues

    26/47

    COMPSCI 10526

    public Object dequeue() throws QueueException {

    if ( !isEmpty() ) {ObjectqueueFront= items[ front];front= ( front+ 1 ) %MAX_QUEUE;--count;return queueFront;

    } else { throw QueueException("Queue Exception on dequeue: Queue empty ) ;

    }

    } // end dequeue

    Fig. 8-10

    Array-Based Implementation

    ADT Queue

  • 8/13/2019 CS105 Queues

    27/47

    COMPSCI 10527

    Array-Based Implementation!front

    andback

    cannot be used to distinguish between queue-

    full and queue-empty conditions for a circular array

    Fig. 8-11: (a) front passes back when the queue becomes empty

    ADT Queue

  • 8/13/2019 CS105 Queues

    28/47

    COMPSCI 10528

    Array-Based Implementation

    Fig. 8-11: (b) back catches up to frontwhen the queue becomes full

    ADT Queue

  • 8/13/2019 CS105 Queues

    29/47

    COMPSCI 10529

    Fig. 8-12: A more efficient circular implementation:a) a full queue; b) an empty queue

    DeclareMAX_QUEUE + 1locations for the array items,but use onlyMAX_QUEUEofthem for queue items

    Array-Based Implementation

    ADT Queue

  • 8/13/2019 CS105 Queues

    30/47

    COMPSCI 10530

    ADT Listcan be used to represent the items in a queue dequeue()as list.remove(1)peek()as list.get(1) enqueue(newItem)as

    list.add(list.size()+1, newItem)

    Fig.8-13

    Implementation that Uses ADT List

    ADT Queue

  • 8/13/2019 CS105 Queues

    31/47

    COMPSCI 10531

    public class QueueListBasedimplements QueueInterface {

    private ListReferenceBasedlist;

    // default constructor

    public QueueListBased(){list= new ListReferenceBased();

    }

    public void enqueue( Object newItem) {

    list.add( list.size() + 1, newItem );

    }// end enqueue

    ADT List Implementation

    ADT Queue

  • 8/13/2019 CS105 Queues

    32/47

    COMPSCI 10532

    public Object dequeue()throws QueueException {

    if ( !isEmpty() ) {// queue is not empty; remove front

    Object queueFront= list.get(1);

    list.remove(1);return queueFront;

    } else {throw new QueueException(

    "Queue exception on dequeue: queue empty");}

    } // end dequeue}// end class QueueListBased}

    ADT ListImplementation

    ADT Queue

  • 8/13/2019 CS105 Queues

    33/47

    COMPSCI 10533

    ! All implementations are ultimatelyeither array-based or reference-based

    ! Fixed size versus dynamic size! A statically allocated array prevents the enqueueoperation

    from adding an item to the queue if the array is full! A resizable array or a reference-based implementation does

    not impose this restriction on the enqueueoperation

    ! A reference-based linked list implementation ismore efficient

    ! The ADT list implementation is simpler to write

    Comparing Implementations

    ADT Queue

  • 8/13/2019 CS105 Queues

    34/47

    COMPSCI 10534

    !Three data structures Linked List, Stack, Queue! All of their operations are defined in terms of the positions of their

    data items

    ! Stackand Queueare very similar! Only their end positions can be accessed: FIFO or LIFO

    ! createStackand createQueue! stack isEmptyand queue isEmpty!pushand enqueue!popand dequeue! stackpeekand queuepeek

    ! Linked List allows to insert into, delete from andinspect at any positions of the list! ADT listoperations generalise stack and queue operations:

    ! length! add,remove, get

    Position-oriented ADTs

    ADT Queue

  • 8/13/2019 CS105 Queues

    35/47

    COMPSCI 10535

    !Java Collection Framework has a queue interface called Queue! Like the Listinterface, Queueis derived from the interface Collection

    public interface Queue extendsCollection {E element() throwsNoSuchElementException;// Retrieves, but does not remove head; if this queue is empty throws exception

    booleanoffer( E o );

    // Inserts the specified element into this queue, if possibleE peek();

    // Retrieves, but does not remove head; returns null if this queue is empty

    E poll();

    // Retrieves and removes head, or null if this queue is empty

    E remove() throwsNoSuchElementException;

    // Retrieves and removes head; if this queue is empty throws exception

    } // end Queue

    The JCF Interface Queue

    ADT Queue

  • 8/13/2019 CS105 Queues

    36/47

    COMPSCI 10536

    Application: Simulation

    !Simulation: a technique for modelling the behaviour ofboth natural and human-made systems

    ! Goal! Generate statistics summarising the performance of an existing

    system

    ! Predict the performance of a proposed system! An example: Behaviour of a bank how to optimise?

    ! Reduce number of complaints from its customers about how longthey have to wait for service from banks tellers

    ! Before hiring one more teller: evaluate the approximate averagetime that a customer has to wait

    ! To spend a few days and measure with a stopwatch: not an excitingprospect

    ADT Queue

  • 8/13/2019 CS105 Queues

    37/47

    COMPSCI 10537

    Application: Simulation! More appealing: Computer simulation of the behavior of a bank

    ! First step: a math model that captures the relevant information aboutthe system

    ! How many tellers does the bank employ?! How often do customers arrive?

    ! Central to a simulation is the notion of simulated time:

    Fig.8-14: A simulated blank line at time 0, 12, 20, 38,

    ADT Queue

  • 8/13/2019 CS105 Queues

    38/47

    Application: Simulation

    !If the model accurately describes the real-world system, asimulation can accurately predict the systems performance

    ! Predict the average time a customer has to wait before receiving service! Evaluate proposed changes to the real-world system

    ! Predict the effect of hiring more tellers in the bank: whether a decrease in theaverage waiting time for a customer justifies the cost of additional tellers

    ! To gather the information one needs for decision, the simulationof lines of customers runs for a certain specified period of time

    ! In the example on Slide 37:! Customer 1 waits 0 minutes to begin a transaction,! Customer 2 had to wait 18 minutes to begin a transaction! An average wait of 9 minutes

    COMPSCI 10538 ADT Queue

  • 8/13/2019 CS105 Queues

    39/47

    COMPSCI 10539

    Application: Simulation! How to determine when certain events occur?

    ! By studying the real world, mathematicians have learned to model eventssuch as the arrival of people using techniques from probability theory

    ! This statistical information is incorporated into the math model of thesystem and is used to generate events reflecting the real world

    !An event-drivensimulation:! Uses the events generated by a mathematical model! Simulated time is advanced to the time of the next event, e.g.! 20 5 -- the 1stcustomer arrives 20 min into simulation; his service takes 5 min! 22 4 -- the 2ndcustomer arrives 22 min; his service takes 4 min! 23 2 -- etc! 30 3

    ADT Queue

  • 8/13/2019 CS105 Queues

    40/47

    Application: Simulation

    Time Event

    20 Customer 1 enters bank and begins transaction

    22 Customer 2 enters bank and stands at end of line

    23 Customer 3 enters bank and stands at end of line

    25 Customer 1 departs; customer 2 begins transaction

    29 Customer 2 departs; customer 3 begins transaction

    30 Customer 4 enters bank and stands at end of line

    31 Customer 3 departs; customer 4 begins transaction

    34 Customer 4 departs

    COMPSCI 10540 ADT Queue

  • 8/13/2019 CS105 Queues

    41/47

    COMPSCI 10541

    Application: Simulation

    !A time-drivensimulation! Simulated time is advanced by a single time unit! The time of an event, such as an arrival or departure, is

    determined randomly and compared with a simulated clock

    ! Bank simulation is concerned with arrival events anddeparture events! Arrival events indicate the arrival at the bank of a new

    customer! External events: the input file specifies the times at which the arrival

    events occur

    ! Departure events indicate the departure from the bank of acustomer who has completed a transaction! Internal events: the simulation determines the times at which these

    events occur

    ADT Queue

  • 8/13/2019 CS105 Queues

    42/47

    COMPSCI 10542

    An event listis needed to implement an event-driven simulation! The list keeps track of arrival and departure events that will occur but

    have not occurred yet

    ! The list contains at most one arrival event and one departure event

    Fig. 8-15: A typical instance of the event list

    Application: Simulation

    ADT Queue

  • 8/13/2019 CS105 Queues

    43/47

    Application: Simulation

    !4 possible configurations of an event list

    ! Initially: the event list contains an arrival event A after reading itfrom the input file but before processing it

    ! Event list: A (initial state)! Generally, the event list contains exactly two events: one arrival

    event A and one departure event D! Event list: D A (general case next event is a departure)! Event list: A D (general case next event is an arrival)

    ! If the tellers line is empty after the departure (like initial state)! Event list: A (a departure leaves the tellers line empty)

    ! If the end of the input file after processing the arrival event:! Event list: D (the input has been exhausted)

    COMPSCI 10543 ADT Queue

  • 8/13/2019 CS105 Queues

    44/47

    Simulation with the ADT Queue+simulate()

    +processArrival(inarrivalEvent:Event,

    inarrivalFile: File,

    inoutanEventList: EventList,

    inoutbankQueue: Queue)

    +processDeparture( indepartureEvent: Event,

    inoutanEventList: EventList,

    inoutbankQueue: Queue)

    +createEventList()

    +isEmpty():boolean

    +insert( inanEvent: Event)

    COMPSCI 10544 ADT Queue

  • 8/13/2019 CS105 Queues

    45/47

    COMPSCI 10545

    Summary

    !The definition of the queue operations gives the ADTqueue first-in, first-out (FIFO) behaviour

    ! A reference-based implementation of a queue useseither

    ! A circular linked list! A linear linked list with a head reference and a tail reference

    ! An array-based implementation of a queue is proneto rightward drift! A circular array eliminates the problem of rightward drift

    ADT Queue

  • 8/13/2019 CS105 Queues

    46/47

    COMPSCI 10546

    Summary

    !To distinguish between the queue-full and queue-empty conditions in a queue implementation that

    uses a circular array, you can

    ! Count the number of items in the queue! Use a fullflag! Leave one array location empty

    ! Models of real-world systems often use queues! The event-driven simulation in Chapter 8 of the textbook

    uses a queue to model a line of customers in a bank

    ADT Queue

  • 8/13/2019 CS105 Queues

    47/47

    COMPSCI 10547

    Summary

    !Simulations:! Central to a simulation is the notion of simulated time! In a time-driven simulation simulated time is advanced by a

    single time unit

    ! In an event-driven simulation simulated time is advanced tothe time of the next event

    ! To implement an event-driven simulation: maintain anevent list containing events that have not yet

    occurred

    ADT Queue