720 likes | 4.54k Views
Queues. Implementations. Outline. Queues Basic operations Examples of use Implementations Array-based and linked list-based. Building a Queue Class. In a queue, new values are always added at the front or head of the list
E N D
Queues Implementations
Outline • Queues • Basic operations • Examples of use • Implementations • Array-based and linked list-based
Building a QueueClass • In a queue, • new values are always addedat the front or head of the list • values are removedfrom the opposite end of the list, the rear or tail • Examples of queues • checkout at supermarket • vehicles at toll booth • ticket line at movies • Queue exhibits First-In-First-Out behavior
D C B A Queue • Queue: First In First Out (FIFO) • Toll Station • Car comes, pays, leaves • Check-out in Big Y market • Customer comes, checks out and leaves Output Input
Queues in a Computer System • When a process (program) requires a certain resource • Printer • disk access on a network • characters in a keyboard buffer. When you enter data into the computer, the characters are kept in queue in a buffer until the operating system can deal with them.
More Examples of Queue • In our daily life • Airport Security Check • Cinema Ticket Office • Bank, ATM
Examples • Queue is a British word for line. • Expect O ( 1 ) time per queue operation because it is similar to a stack. The word "queueing" and its derivatives are the only English words with five consecutive vowels.
Applications • Queues are also useful for storing pending work: • Shortest paths problem (minimize the number of connecting flights between two arbitrary airports) • Operating Systems use queues to schedule tasks. • Queues are often used in simulations e.g. • Simulating traffic at an intersection by creating a growing line of automobiles waiting for the light to change.
Abstract Data Types • Queue • Operating on both ends • Operations: EnQueue(in),DeQueue(out) enqueue dequeue C B A front rear
Printing Job Management • Many users send their printing jobs to ECS public printer • Printer will put them into a queue according to the arrival time and print the jobs one by one • These printing documents are A.doc, B.doc, C.doc and D.doc
Printing Queue • A.doc B.doc C.doc arrive to printer. Now printing A.doc C B A C B A.doc is finished. Now printing B.doc D.doc comes D C B Now still printing B.doc D C B.doc is finished. Now printing C.doc D C.doc is finished. Now printing D.doc
First-in First-out (FIFO) The first one enqueued is the first one dequeued. (FIFO) When we enqueue entries in the queue and then dequeue them one by one, we will get the items in the same order. A, B, C come out
Implementing a Queue Class • Implement as a LinkedList • insertions and deletions from either end are efficient, occur in constant O(1) time • good choice • Implement as an ArrayList • Not as simple • adding values at one end, removing at other end require multiple shifts • Need to use a circular array
Implementing a QueueClass • Build a Queue from scratch • build a linked structure to store the queue elements Attributes required • A handle for the head node - Head • handle for tail node - Tail • integer to store number of values in the queue - count • use LinearNode
QueueStructure aQueue Head Size Tail n . . . value0 value1 . . . valuen-1
Operations • enqueue • add a new item at the rear • dequeue • remove a item from the front • isEmpty • check whether the queue is empty or not • size • return the number of items in the queue • peek • return the front item
Abstract Data Type • Same as Stack class, we use the T data type • Use an Arrayqueue, which stores all items that come in. • T Queue[ ]; • Other implementation with a Linked list we will address later.
Queues: Simple Idea • Store items in an array with front item at index zero and back item at index rear. We will add items at one end of a queue and remove them from the other end. • Enqueue is easy: increment rear by one and store the new item in data[rear]. • To get the next item, we retrieve data[front]. Dequeue is inefficient: all elements have to be shifted up one place. • Result: Dequeue will be O( N ).
Two Solutions • Shifting all items to front in the array when dequeue operation. ( Too Costly… ) A leaves n-1 3 2 1 0 n-1 3 2 1 0 … … C B A … … C B rear=3 front=0 rear=2 front=0
a b c d Rear a b c d Better Idea • Keep a Frontindex. • To Dequeue, increment front. Front Front Rear Front
Array Implementation of Queue n-1 3 2 1 0 D C B A rear front Max_Size After A leaves, n-1 3 2 1 0 D C B rear front Max_Size
Circular Implementation • This implementation is O( 1 ) per operation. The problem is that there will be many empty places in the front of array and rear is always incremented. • So we will quickly reach the end of the array. • It is possible after Array.length enqueues, we are full, even if queue is logically nearly empty. • Solution: use wraparound to reuse the cells at the start of the array. To increment, add one, but if that goes past end, reset to zero using the mod operator.
Circular Example - Array • Both Front and Rear wraparound as needed. Rear Front b c d e f Rear Front g b c d e f
Circular Array • Wrapped around array rear=3 3 2 C front=0 1 n-1 3 2 1 0 B … … C B A 0 A n-1 rear=3 front=0
EnQueue & DeQueue In Circular Array • EnQueue • rear = (rear + 1) MOD n • DeQueue • front = (front + 1) MOD n rear=3 front=1 3 3 2 2 C C 1 1 B B 0 A 0 n-1 n-1
Empty/Full In Circular Array • When rear equals front, Queue is empty • When (rear + 1) MOD n equals front, Queue is full • Circular array with capacityn at most can hold n-1 items.
Java Implementation- Array • Mostly straightforward; maintain: • Front • Rear • Current number of items in queue • Only tricky part is array doubling because contiguity of wraparound must be maintained.
EnsureCapacity • Invariant of the Queue ADT (Array version): • The number of items is stored in the instance variable size . • For a non-empty queue the items are stored in a circular array beginning at data[front] and continuing to data[rear]. • For an empty queue, size is zero and data is a reference to an array, but no reference is kept to front and rear
Implemention of EnsureCapacity • If size is non-zero, and front is less than rear, then a new array is allocated and the data from data[front] to data[rear] is copied using System.arraycopy. • If size is non-zero and front is greater rear, a new array is allocated . The items from data[front] to the end are copied followed by the items from data[0] to data[rear]. Two separate calls to System.arraycopy are activated.
ARRAY IMPLEMENTATION rear front The EnsureCapacity method requires several steps before a new array is created and the elements copies. C D ? A B data A B C D ? ? ? ? ? ? ? front rear Bigger Array
Linked List Implementation • The class LinkedQueue has the following invariant: • Size -The number of items in the queue • The items are stored in linked list with front at the head node and rear at the final node. • The instance variable front is the head reference and rear is the tail reference. • For the empty queue, both front and rear are null.
Code for Enqueue • In the case of the empty list, both rear and front must be null: • LinearNode<T> node = new LinearNode<T>(item, null); if( isEmpty()) { // insert first item front = node; rear = front; } else { // insert item that is not first, add to end rear.next=node; rear = rear.next;// or rear = node }
Code for Dequeue • In the case of the empty list, both rear and front must point to the first node: • if( isEmpty()) • { // throw an exception • } • //* Remove the first object from the queue - same as removeFirst • public T dequeue() throws EmptyQueueException { • // store element in Front node in a variable of type T • // advance front to the next node • // decrement count • if (count == 0) • //set tail to null; // the queue is now empty • // return variable of type T; • } • } 6/9/2014 35
Customer Service In Fleet Bank • Suppose there is only one customer service available in Fleet Bank in Saturday morning • In every 3 minutes, a new customer arrives at the end of waiting line • Each customer will need 5 minutes for the service • Print out the information after the first 30 minutes • What variables do we need? • The time of arriving and leaving for each customers • How many customers are in the line? • Who is the current serving customer?
public class BankServiceQueue { public void run() { //Create a new queue QueuePT<T> que = new ArrayQueuePT<T>(100); int time = 0; int incustomer = 0; int servicetime = 0;
Customer In Service // what's going on in 30 minutes while ( time <= 30 ) { // if queue is not empty, one customer service is working // customer leaves when finished service, service time is 5 minutes if( servicetime == 5 ) { dequeue start another job } }
New Customer Comes // in every 3 minutes, there is a new customer coming. if( time%3==0 ) { // enqueue a customer // print it out and start all over again } time = time + 1; }
Priority Queues • In an operating system which queues up tasks to be performed by the CPU, some jobs are more important than others. E. G. answering a system call over printing a file. • Priorities are assigned to the jobs. A Priority Queue stores not only the item but its priority. • Jobs are dequeued according to their priority and jobs with the same priority are dequeued according to which entered first.
Priority Queue ADT • In some operating systems, there are multiple queues with different priorities. • An array of queues might be used if the number of priorities is sufficiently small.
Priority Queue --- Air Travel • Only one check-in service in United Airline at airport • Two waiting lines for passengers • one is First class service • the other is Economy class service • Passengers in the first-class waiting line have higher priority to check in than those in the economy-class waiting line.
Priority Queue • Two queues • one is high priority queue • the other is low priority queue • Service rules: • First serve the people in high priority queue • If no passengers are in high priority queue, serve the passengers in low priority queue
Two Queues • High Priority Queue, will come in hpQue • Low Priority Queue, will come in lpQue High Priority Queue Check In Customers coming in H D C G F E B A Low Priority Queue
Pseudocode For Arrival Passengers Arrival: if( new Passenger comes ) { if( is First Class) hpQue.enqueue( new Passenger ); else lpQue.enqueue( new Passenger ); }
Pseudocode For Service Check-In Service: if( hpQue is not empty ) { serve the passenger from high priority queue, hpQue.dequeue(); } else { serve the passenger from low priority queue, lpQue.dequeue(); }
Implementation for Queue public class ArrayQueuePT { private final static int DEFAULT_CAPACITY = 100; // suppose the default capacity for this queue is 100. private T queue[ ]; // The array that holds the items private int rear, front; // index of rear, front item in the queue; }
ArrayQueuePT Constructor // Creates a queue with the default capacity public ArrayQueuePT<T> () { this(DEFAULT_CAPACITY); // creates this queue with the default capacity } // Creates a queue with a user-specified capacity public ArrayQueuePT (int capacity) { if (capacity < 2) throw new IllegalArgumentException ("Capacity must be > 1"); queue =<T> new Object[capacity]; rear = front = 0; }
ArrayQueuePT --- Size() • How many items currently in the queue? public int size() { // could use a counter if( rear >= front ) return rear – front; else return queue.length + rear – front; }