Queues CSI 1101 N. El Kadri. 2 Definitions A queue is a linear abstract data type such that...

51
Queues CSI 1101 N. El Kadri

Transcript of Queues CSI 1101 N. El Kadri. 2 Definitions A queue is a linear abstract data type such that...

Page 1: Queues CSI 1101 N. El Kadri. 2 Definitions A queue is a linear abstract data type such that insertions are made at one end, called the rear, and removals.

Queues

CSI 1101N. El Kadri

Page 2: Queues CSI 1101 N. El Kadri. 2 Definitions A queue is a linear abstract data type such that insertions are made at one end, called the rear, and removals.

2

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.

Page 3: Queues CSI 1101 N. El Kadri. 2 Definitions A queue is a linear abstract data type such that insertions are made at one end, called the rear, and removals.

3

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.

Page 4: Queues CSI 1101 N. El Kadri. 2 Definitions A queue is a linear abstract data type such that insertions are made at one end, called the rear, and removals.

4

Example

class Simple {public static void main( String[] args ) {

Queue queue = new QueueImplementation(); for ( int i=0; i<10; i++ )

queue.enqueue( new Integer( i ) ); while ( ! queue.isEmpty() )

System.out.println( queue.dequeue() ); }

}

What does it print?

Page 5: Queues CSI 1101 N. El Kadri. 2 Definitions A queue is a linear abstract data type such that insertions are made at one end, called the rear, and removals.

5

q = new QueueImpl() q []q.enqueue(a) q [a]q.enqueue(b) q [a,b]q.enqueue(c) q [a,b,c]q.enqueue(d) q [a,b,c,d]q.dequeue() a q [b,c,d]q.dequeue() b q [c,d]q.enqueue(e) q [c,d,e]q.dequeue() c q [d,e]q.dequeue() d q [e]

Elements of a queue are processed in the same order as the 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 first-serve.

Page 6: Queues CSI 1101 N. El Kadri. 2 Definitions A queue is a linear abstract data type such that insertions are made at one end, called the rear, and removals.

6

Implementations

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

Page 7: Queues CSI 1101 N. El Kadri. 2 Definitions A queue is a linear abstract data type such that insertions are made at one end, called the rear, and removals.

7

Today’s Topics

• Queue– Implementation of Queue– Usage of Queue

Page 8: Queues CSI 1101 N. El Kadri. 2 Definitions A queue is a linear abstract data type such that insertions are made at one end, called the rear, and removals.

8

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

• More examples: Printer, Office Hours, …

ABCD OutputInput

Page 9: Queues CSI 1101 N. El Kadri. 2 Definitions A queue is a linear abstract data type such that insertions are made at one end, called the rear, and removals.

9

More Examples of Queue

• In our daily life– Airport Security Check– Cinema Ticket Office– Bank, ATM– Anything else ?

Page 10: Queues CSI 1101 N. El Kadri. 2 Definitions A queue is a linear abstract data type such that insertions are made at one end, called the rear, and removals.

10

What Is Queue

• Queue is an abstract data type• Adding an entry at the rear • Deleting an entry at the front

frontfrontrearrear

AddingAdding DeletingDeletingABC

Page 11: Queues CSI 1101 N. El Kadri. 2 Definitions A queue is a linear abstract data type such that insertions are made at one end, called the rear, and removals.

11

Abstract Data Types

• Queue– Operating on both ends– Operations: EnQueue(in),

DeQueue(out)

frontfrontrearrear

enqueueenqueuedequeuedequeue

ABC

Page 12: Queues CSI 1101 N. El Kadri. 2 Definitions A queue is a linear abstract data type such that insertions are made at one end, called the rear, and removals.

12

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

Page 13: Queues CSI 1101 N. El Kadri. 2 Definitions A queue is a linear abstract data type such that insertions are made at one end, called the rear, and removals.

13

Applications of Queue

• Printing Job Management• Packet Forwarding in Routers• Message queue in Windows• I/O buffer

Page 14: Queues CSI 1101 N. El Kadri. 2 Definitions A queue is a linear abstract data type such that insertions are made at one end, called the rear, and removals.

14

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

Page 15: Queues CSI 1101 N. El Kadri. 2 Definitions A queue is a linear abstract data type such that insertions are made at one end, called the rear, and removals.

15

Printing Queue

Now printing A.doc

A.doc is finished. Now printing B.doc

Now still printing B.docD.doc comes

• A.doc B.doc C.doc arrive to printer.ABC

BC

BCD

CD

D

B.doc is finished. Now printing C.doc

C.doc is finished. Now printing D.doc

Page 16: Queues CSI 1101 N. El Kadri. 2 Definitions A queue is a linear abstract data type such that insertions are made at one end, called the rear, and removals.

16

First-in First-out (FIFO)

When we enqueue entries in the queue and then dequeue them one by one, we will get the items in the same order.

When we enqueue entries in the queue and then dequeue them one by one, we will get the items in the same order.

The first one enqueued is the first one dequeued. (FIFO)

The first one enqueued is the first one dequeued. (FIFO)

ABC

A

AB

BC

C

A, B, C come in

A, B, C come out

Page 17: Queues CSI 1101 N. El Kadri. 2 Definitions A queue is a linear abstract data type such that insertions are made at one end, called the rear, and removals.

17

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?

Page 18: Queues CSI 1101 N. El Kadri. 2 Definitions A queue is a linear abstract data type such that insertions are made at one end, called the rear, and removals.

18

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

Page 19: Queues CSI 1101 N. El Kadri. 2 Definitions A queue is a linear abstract data type such that insertions are made at one end, called the rear, and removals.

19

Array Implementation of Queue

B AD C

Max_Size rear front

After A leaves,

BD C

Max_Size rear front

1 0n-1 3 2

1 0n-1 3 2

Page 20: Queues CSI 1101 N. El Kadri. 2 Definitions A queue is a linear abstract data type such that insertions are made at one end, called the rear, and removals.

20

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

• isFull– check whether the queue is full or not

• size– return the number of items in the queue

• peek– return the front item

Page 21: Queues CSI 1101 N. El Kadri. 2 Definitions A queue is a linear abstract data type such that insertions are made at one end, called the rear, and removals.

21

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?

Y X ……1 0n-1 3 2

rear front

Page 22: Queues CSI 1101 N. El Kadri. 2 Definitions A queue is a linear abstract data type such that insertions are made at one end, called the rear, and removals.

22

Two Solutions

• Shifting all items to front in the array when dequeue operation. ( Too Costly… )

• Wrapped around array ---- Circular Array

B A …… C1 0n-1 3 2

rear=3 front=0

C B ……1 0n-1 3 2

rear=2 front=0

A leaves

Page 23: Queues CSI 1101 N. El Kadri. 2 Definitions A queue is a linear abstract data type such that insertions are made at one end, called the rear, and removals.

23

Circular Array

• Wrapped around array

B A …… C1 0n-1 3 2

rear=3 front=0

A

BC

0

23

n-1

1

rear=3

front=0

Page 24: Queues CSI 1101 N. El Kadri. 2 Definitions A queue is a linear abstract data type such that insertions are made at one end, called the rear, and removals.

24

EnQueue & DeQueue In Circular Array

• EnQueue– rear = (rear + 1) MOD n

• DeQueue– front = (front + 1) MOD n

A

BC

0

23

n-1

1

rear=3

BC

0

23

n-1

1

front=1

Page 25: Queues CSI 1101 N. El Kadri. 2 Definitions A queue is a linear abstract data type such that insertions are made at one end, called the rear, and removals.

25

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.

Page 26: Queues CSI 1101 N. El Kadri. 2 Definitions A queue is a linear abstract data type such that insertions are made at one end, called the rear, and removals.

26

Implementation for Queue

public class ArrayQueuePT {

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;

}

Page 27: Queues CSI 1101 N. El Kadri. 2 Definitions A queue is a linear abstract data type such that insertions are made at one end, called the rear, and removals.

27

ArrayQueuePT Constructor// Creates a queue with the default capacitypublic ArrayQueuePT () {

this(DEFAULT_CAPACITY);}// Creates a queue with a user-specified capacitypublic ArrayQueuePT (int capacity) {

if (capacity < 2)throw new IllegalArgumentException ("Capacity

must be > 1");queue = new Object[capacity];rear = front = 0;

}

Page 28: Queues CSI 1101 N. El Kadri. 2 Definitions A queue is a linear abstract data type such that insertions are made at one end, called the rear, and removals.

28

ArrayQueuePT --- Size()

• How many items currently in the queue?

public int size() {

if( rear >= front )

return rear – front;

else

return queue.length + rear – front;

}

Page 29: Queues CSI 1101 N. El Kadri. 2 Definitions A queue is a linear abstract data type such that insertions are made at one end, called the rear, and removals.

29

ArrayQueuePT --- isEmpty/isFull// check whether the queue is emptypublic boolean isEmpty() {

return rear == front;}// check whether the queue is fullpublic boolean isFull() {

return size() == queue.length-1;}

Page 30: Queues CSI 1101 N. El Kadri. 2 Definitions A queue is a linear abstract data type such that insertions are made at one end, called the rear, and removals.

30

ArrayQueuePT --- enqueue()

public void enqueue(Object item) {if (item == null)

throw new IllegalArgumentException ("Item is null");if (isFull())

throw new IllegalStateException (“Queue is full");

queue[rear] = item; rear = (rear + 1)%queue.length;}

Page 31: Queues CSI 1101 N. El Kadri. 2 Definitions A queue is a linear abstract data type such that insertions are made at one end, called the rear, and removals.

31

ArrayQueuePT --- dequeue()public Object pop( ) {

if (isEmpty())throw new IllegalStateException (“Queue

is empty");Object frontItem = queue[front];

queue[front] = null; front = (front + 1)%queue.length; return frontItem;}

Page 32: Queues CSI 1101 N. El Kadri. 2 Definitions A queue is a linear abstract data type such that insertions are made at one end, called the rear, and removals.

32

ArrayQueuePT -- peek()

public Object peek() {

if (isEmpty())

throw new IllegalStateException (“Queue is empty");

return queue[front];

}

Page 33: Queues CSI 1101 N. El Kadri. 2 Definitions A queue is a linear abstract data type such that insertions are made at one end, called the rear, and removals.

33

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, isFull,

isEmpty

Page 34: Queues CSI 1101 N. El Kadri. 2 Definitions A queue is a linear abstract data type such that insertions are made at one end, called the rear, and removals.

34

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 {

… …}

Page 35: Queues CSI 1101 N. El Kadri. 2 Definitions A queue is a linear abstract data type such that insertions are made at one end, called the rear, and removals.

35

Interface for Queue

public interface QueuePT { public boolean isEmpty(); public boolean isFull(); public Object peek(); public Object dequeue(); public void enqueue(Object item); public int size();}

Page 36: Queues CSI 1101 N. El Kadri. 2 Definitions A queue is a linear abstract data type such that insertions are made at one end, called the rear, and removals.

36

Implementation of ArrayQueuePT Class

• Example: QueuePT.java, ArrayQueuePT.java

public class ArrayQueuePT implements QueuePT {

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

Page 37: Queues CSI 1101 N. El Kadri. 2 Definitions A queue is a linear abstract data type such that insertions are made at one end, called the rear, and removals.

37

Create an object of ArrayQueuePT// create a queue with default capacityQueuePT myqueue = new ArrayQueuePT();

// create a queue with 1024 elementsQueuePT registry = new

ArrayQueuePT(1024);

Page 38: Queues CSI 1101 N. El Kadri. 2 Definitions A queue is a linear abstract data type such that insertions are made at one end, called the rear, and removals.

38

Using ArrayQueuePT

• enqueue and dequeue characters in Queue myque– myque.enqueue( new Character(‘a’) )– char ch = ((Character)myque.dequeue()).charValue()

• enqueue and dequeue Employee in Queue registry– registry.enqueue( new Employee(“Hamad”,

“5456”) )– Employee emp = (Employee) registry.dequeue();

Page 39: Queues CSI 1101 N. El Kadri. 2 Definitions A queue is a linear abstract data type such that insertions are made at one end, called the rear, and removals.

39

Printing Job Management4 documents are ready to print• Print the printer status

– new document comes– which document is finished

• Using ArrayQueuePT

• Complete Example: – PrintingJobQueue.java

Page 40: Queues CSI 1101 N. El Kadri. 2 Definitions A queue is a linear abstract data type such that insertions are made at one end, called the rear, and removals.

40

New Printing Jobs comepublic void printstatus() { QueuePT que = new ArrayQueuePT( ); //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" );

Page 41: Queues CSI 1101 N. El Kadri. 2 Definitions A queue is a linear abstract data type such that insertions are made at one end, called the rear, and removals.

41

Finishing Printing Jobs

// print the printer status

System.out.println("\nPrinting job: there are " + que.size() + " jobs in the queue");

System.out.println(" " + que.dequeue() + " is Finished");

System.out.println(" " + que.dequeue() + " is Finished");

System.out.println(" " + que.dequeue() + " is Finished");

System.out.println(" " + que.dequeue() + " is Finished");

}

Page 42: Queues CSI 1101 N. El Kadri. 2 Definitions A queue is a linear abstract data type such that insertions are made at one end, called the rear, and removals.

42

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?

Page 43: Queues CSI 1101 N. El Kadri. 2 Definitions A queue is a linear abstract data type such that insertions are made at one end, called the rear, and removals.

43

Customer Service Queue• Complete example:

BankServiceQueue.javapublic void run( ) {

// Create a new queue QueuePT que = new ArrayQueuePT(100);

int time = 0; // in minutes int incustomer = 0; // secquence of

customers int servicetime = 0; // service times

Page 44: Queues CSI 1101 N. El Kadri. 2 Definitions A queue is a linear abstract data type such that insertions are made at one end, called the rear, and removals.

44

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

Page 45: Queues CSI 1101 N. El Kadri. 2 Definitions A queue is a linear abstract data type such that insertions are made at one end, called the rear, and removals.

45

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

Page 46: Queues CSI 1101 N. El Kadri. 2 Definitions A queue is a linear abstract data type such that insertions are made at one end, called the rear, and removals.

46

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" ); }}

Page 47: Queues CSI 1101 N. El Kadri. 2 Definitions A queue is a linear abstract data type such that insertions are made at one end, called the rear, and removals.

47

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.

Page 48: Queues CSI 1101 N. El Kadri. 2 Definitions A queue is a linear abstract data type such that insertions are made at one end, called the rear, and removals.

48

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

Page 49: Queues CSI 1101 N. El Kadri. 2 Definitions A queue is a linear abstract data type such that insertions are made at one end, called the rear, and removals.

49

Two Queues• High Priority Queue, will come in hpQue• Low Priority Queue, will come in lpQue

D CHCheck In

G F E B A

High Priority Queue

Low Priority Queue

Customers coming in

Page 50: Queues CSI 1101 N. El Kadri. 2 Definitions A queue is a linear abstract data type such that insertions are made at one end, called the rear, and removals.

50

Pseudocode For Arrival

Passengers Arrival: if( new Passenger comes ) { if( is First Class) hpQue.enqueue( new

Passenger ); else lpQue.enqueue( new

Passenger ); }

Page 51: Queues CSI 1101 N. El Kadri. 2 Definitions A queue is a linear abstract data type such that insertions are made at one end, called the rear, and removals.

51

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();

}