# Queues CSI 1101 N El Kadri Definitions A

• Slides: 51

Queues CSI 1101 N. El Kadri

Definitions • A queue is a linear abstract data type such that insertions are made at one end, called the rear, and removals are made at the other end, called the front. • Queues are sometimes called FIFOs: first-in first-out. enqueue() Queue dequeue() The two basic operations are: • enqueue: adds an element to the rear of the queue. • dequeue: removes and returns the element at the front of the queue. Software queues are similar to physical ones: queuing at the supermarket, at the bank, at cinemas, etc. 2

Applications • Shared resources management (system programming): – Access to the processor; – Access to the peripherals such as disks and printers. • Application programs: – Simulations; – Generating sequences of increasing length over a finite size alphabet; – Navigating through a maze. 3

Example class Simple { public static void main( String[] args ) { Queue queue = new Queue. Implementation(); for ( int i=0; i<10; i++ ) queue. enqueue( new Integer( i ) ); while ( ! queue. is. Empty() ) System. out. println( queue. dequeue() ); } } What does it print? 4

q = new Queue. Impl() q. enqueue(a) q. enqueue(b) q. enqueue(c) q. enqueue(d) q. dequeue() a q. dequeue() b q. enqueue(e) q. dequeue() c q. dequeue() d q [] q [a, b] q [a, b, c, d] q [b, c, d] q [c, d, e] q [e] Elements of a queue are processed in the same order as they are inserted into the queue, here “a” was the first element to join the queue and it was the first to leave the queue: first-come firstserve. 5

Implementations • Just like stacks, there are two families of implementations. – Array-based; – Linked-structure. 6

Today’s Topics • Queue – Implementation of Queue – Usage of Queue 7

Queue • Queue: First In First Out (FIFO) Input D C B A Output • Toll Station – Car comes, pays, leaves • Check-out in Big Y market – Customer comes, checks out and leaves • More examples: Printer, Office Hours, … 8

More Examples of Queue • In our daily life – Airport Security Check – Cinema Ticket Office – Bank, ATM – Anything else ? 9

What Is Queue • Queue is an abstract data type • Adding an entry at the rear • Deleting an entry at the front Adding Deleting C B A rear front 10

Abstract Data Types • Queue – Operating on both ends – Operations: En. Queue(in), De. Queue(out) enqueue C B A rear dequeue front 11

Queue is FIFO ( First-In First-Out) A queue is open at two ends. You can only add entry (enqueue) at the rear , and delete entry (dequeue) at the front. Note that you cannot add/extract entry in the middle of the queue. 12

Applications of Queue • • Printing Job Management Packet Forwarding in Routers Message queue in Windows I/O buffer 13

Printing Job Management • Many users send their printing jobs to a 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 14

Printing Queue • A. doc B. doc C. doc arrive to printer. C B A C B D. doc comes D C B Now printing A. doc is finished. Now printing B. doc Now still printing B. doc D C B. doc is finished. Now printing C. doc D C. doc is finished. Now printing D. doc 15

First-in First-out (FIFO) The first one enqueued is the first one dequeued. (FIFO) A, B, C come in C B A C 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 16

Question • Queue is an abstract data structure • Item can be Integer, Double, String, Employee, Faculty… • How to implement a general queue for all those types? 17

Abstract Data Type • Same as Stack, we use Object data type instead of int or double or String or other data type • Use an array in queue, which stores all items come in. – Object Queue[ ]; • Other implementations are possible 18

Array Implementation of Queue n-1 3 2 1 0 DCBA Max_Size rear front After A leaves, n-1 3 2 1 0 DCB Max_Size rear front 19

Operations • enqueue – add a new item at the rear • dequeue – remove a item from the front • is. Empty – check whether the queue is empty or not • is. Full – check whether the queue is full or not • size – return the number of items in the queue • peek – return the front item 20

Problem • An array has limited size, once rear is at the end of this array, and there is new item coming in, what can we do? n-1 3 2 1 0 Y X …… rear front 21

Two Solutions • Shifting all items to front in the array when dequeue operation. ( Too Costly… ) n-1 3 2 1 0 …… rear=3 A leaves CBA front=0 n-1 3 2 1 0 …… CB rear=2 front=0 • Wrapped around array ---- Circular Array 22

Circular Array rear=3 • Wrapped around array 2 n-1 3 2 1 0 …… rear=3 CBA front=0 1 B 0 A 3 C n-1 23

En. Queue & De. Queue In Circular Array • De. Queue • En. Queue – rear = (rear + 1) MOD n 2 1 0 n-1 B A 3 rear=3 – front = (front + 1) MOD n front=1 2 C 1 B 3 C 0 n-1 24

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 capacity n at most can hold n-1 items. 25

Implementation for Queue public class Array. Queue. PT { private final static int DEFAULT_CAPACITY = 100; // suppose the default capacity for this queue is 100. private Object queue[ ]; // The array that holds the items private int rear, front; // Index of rear, front item in the queue; } 26

Array. Queue. PT Constructor // Creates a queue with the default capacity public Array. Queue. PT () { this(DEFAULT_CAPACITY); } // Creates a queue with a user-specified capacity public Array. Queue. PT (int capacity) { if (capacity < 2) throw new Illegal. Argument. Exception ("Capacity must be > 1"); queue = new Object[capacity]; rear = front = 0; } 27

Array. Queue. PT --- Size() • How many items currently in the queue? public int size() { if( rear >= front ) return rear – front; else return queue. length + rear – front; } 28

Array. Queue. PT --- is. Empty/is. Full // check whether the queue is empty public boolean is. Empty() { return rear == front; } // check whether the queue is full public boolean is. Full() { return size() == queue. length-1; } 29

Array. Queue. PT --- enqueue() public void enqueue(Object item) { if (item == null) throw new Illegal. Argument. Exception ("Item is null"); if (is. Full()) throw new Illegal. State. Exception (“Queue is full"); queue[rear] = item; rear = (rear + 1)%queue. length; } 30

Array. Queue. PT --- dequeue() public Object pop( ) { if (is. Empty()) throw new Illegal. State. Exception (“Queue is empty"); Object front. Item = queue[front]; queue[front] = null; front = (front + 1)%queue. length; return front. Item; } 31

Array. Queue. PT -- peek() public Object peek() { if (is. Empty()) throw new Illegal. State. Exception (“Queue is empty"); return queue[front]; } 32

Interface • Users don’t need to know how Queue is implemented. • User only need to know how they can operate the Queue. • There are many ways to implement Queue, but all of them have the same interfaces – enqueue, dequeue, peek, is. Full, is. Empty 33

Interface and Implementation Class • Interface contains a skeleton for public operations – No real code for each method – Like function prototype • A class implements interface – Implements every method • Statement: public class myclass implements interface { …… } 34

Interface for Queue public interface Queue. PT { public boolean is. Empty(); public boolean is. Full(); public Object peek(); public Object dequeue(); public void enqueue(Object item); public int size(); } 35

Implementation of Array. Queue. PT Class • Example: Queue. PT. java, Array. Queue. PT. java public class Array. Queue. PT implements Queue. PT { private final static int DEFAULT_CAPACITY = 100; private Object queue[]; // The array holds the queue private int rear, front; // Index of rear, front items in queue 36

Create an object of Array. Queue. PT // create a queue with default capacity Queue. PT myqueue = new Array. Queue. PT(); // create a queue with 1024 elements Queue. PT registry = new Array. Queue. PT(1024); 37

Using Array. Queue. PT • enqueue and dequeue characters in Queue myque – myque. enqueue( new Character(‘a’) ) – char ch = ((Character)myque. dequeue()). char. Value() • enqueue and dequeue Employee in Queue registry – registry. enqueue( new Employee(“Hamad”, “ 5456”) ) – Employee emp = (Employee) registry. dequeue(); 38

Printing Job Management 4 documents are ready to print • Print the printer status – new document comes – which document is finished • Using Array. Queue. PT • Complete Example: – Printing. Job. Queue. java 39

New Printing Jobs come public void printstatus() { Queue. PT que = new Array. Queue. PT( ); //Create a new queue System. out. println("Printing job: Null "); //print the printer status // new printing jobs come, a. doc, b. doc, c. doc, d. doc System. out. println("New printing job: a. doc"); que. enqueue( "a. doc" ); System. out. println("New printing job: b. doc"); que. enqueue( "b. doc" ); System. out. println("New printing job: c. doc"); que. enqueue( "c. doc" ); System. out. println("New printing job: d. doc"); que. enqueue( "d. doc" ); 40

Finishing Printing Jobs // print the printer status System. out. println("n. Printing job: there are " + que. size() + " jobs in the queue"); System. out. println(" " + que. dequeue() + " is Finished"); } 41

Customer Service In Royal Bank • Suppose there is only one customer service available in Royal Bank on 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 – The time of arriving and leaving for each customer – How many customers are in the line? – Who is the current serving customer? 42

Customer Service Queue • Complete example: Bank. Service. Queue. java public void run( ) { // Create a new queue Queue. PT que = new Array. Queue. PT(100); int time = 0; // in minutes int incustomer = 0; // secquence of customers int servicetime = 0; // service times 43

Customer In Service // what's going on in 30 minutes while ( time <= 30 ) { // if queue is not empty, one customer service is working if( que. size()!=0 ) { servicetime = servicetime + 1; // customer leaves when finishing the service, the service time is 5 minutes if( servicetime == 5 ) { String name = (String)que. dequeue(); System. out. println("<< " + name + " leaves at time = " + time); // start to service time for next customer servicetime = 0; } } 44

New Customer Comes // every 3 minutes, there is a new customer coming. if( time%3==0 ) { incustomer = incustomer + 1; String name = "CUSTOMER " + incustomer; que. enqueue( name ); System. out. println(">> " + name + " arrives at time = " + time); } time = time + 1; } 45

Print Status After 30 Minutes // print the status after 30 minutes System. out. println("n=============" ); if( que. size()!=0 ) { System. out. println("There are " + que. size() + " customers in the line" ); System. out. println("The current serving customer is " + que. peek() ); } else { System. out. println("There are no customers in the line" ); } } 46

Priority Queue --- Air Travel • Only one check-in service in Air Canada 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. 47

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 48

Two Queues • High Priority Queue, will come in hp. Que • Low Priority Queue, will come in lp. Que Customers coming in High Priority Queue HDC Check In GF EBA Low Priority Queue 49

Pseudocode For Arrival Passengers Arrival: if( new Passenger comes ) { if( is First Class) hp. Que. enqueue( new Passenger ); else lp. Que. enqueue( new Passenger ); } 50

Pseudocode For Service Check-In Service: if( hp. Que is not empty ) { serve the passenger from high priority queue, hp. Que. dequeue(); } else { serve the passenger from low priority queue, lp. Que. dequeue(); } 51