queues

70
06/21/22 1 Queues Implementations

Upload: mitch

Post on 24-Jan-2016

24 views

Category:

Documents


0 download

DESCRIPTION

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 - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Queues

04/21/23 1

Queues

Implementations

Page 2: Queues

04/21/23 2

Outline

Queues Basic operations Examples of use

Implementations Array-based and linked list-based

Page 3: Queues

04/21/23 3

Building a Queue Class

In a queue, new values are always added at the front or head of the

list values are removed from 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

Page 4: Queues

04/21/23 4

QueueQueue: First In First Out (FIFO)

Toll Station Car comes, pays, leaves

Check-out in Big Y market Customer comes, checks out and leaves

ABCD OutputInput

Page 5: Queues

04/21/23 5

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.

Page 6: Queues

04/21/23 6

More Examples of Queue

In our daily life

Airport Security Check

Cinema Ticket Office

Bank, ATM

Page 7: Queues

04/21/23 7

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.

Page 8: Queues

04/21/23 8

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.

Page 9: Queues

04/21/23 9

Abstract Data Types

Queue Operating on both ends Operations: EnQueue(in), DeQueue(out)

frontfrontrearrear

enqueueenqueuedequeuedequeue

ABC

Page 10: Queues

04/21/23 10

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

Page 11: Queues

04/21/23 11

Printing Queue

ABC Now printing A.doc

BC A.doc is finished. Now printing B.doc

BC Now still printing B.docD.doc comes

D

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

CD

D

B.doc is finished. Now printing C.doc

C.doc is finished. Now printing D.doc

Page 12: Queues

04/21/23 12

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)

Page 13: Queues

04/21/23 13

Implementing a Queue Class

Implement as a LinkedListLinkedList insertions and deletions from either end are efficient,

occur in constant O(1) time good choice

Implement as an ArrayListArrayList Not as simple adding values at one end, removing at other end require

multiple shifts Need to use a circular array

Page 14: Queues

04/21/23 14

Implementing a Queue Class

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

Page 15: Queues

04/21/23 15

Queue Structure

Head Size Tail

n

aQueue

. . .

. . .value0 value1 valuen-1

Page 16: Queues

04/21/23 16

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

Page 17: Queues

04/21/23 17

The QueueADT interface in UML

Page 18: Queues

04/21/23 18

Listing 7.1 Interface

Page 19: Queues

04/21/23 19

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.

Page 20: Queues

04/21/23 20

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

Page 21: Queues

04/21/23 21

Two Solutions

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

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

04/21/23 22

Better Idea

Keep a Front index.

To Dequeue, increment front.

a b c d

Rear

a b c d

FrontFront

Front

Rear

Page 23: Queues

04/21/23 23

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

04/21/23 24

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.

Page 25: Queues

04/21/23 25

Circular Example - Array

Both Front and Rear wraparound as needed.

b c d

b c d

FrontRear

e f

e fg

Front Rear

Page 26: Queues

04/21/23 26

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

04/21/23 27

EnQueue & DeQueue In Circular Array

EnQueue rear = (rear + 1) MOD n

A

BC

0

23

n-1

1

rear=3

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

BC

0

23

n-1

1

front=1

Page 28: Queues

04/21/23 28

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

04/21/23 29

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.

Page 30: Queues

04/21/23 30

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

Page 31: Queues

04/21/23 31

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.

Page 32: Queues

04/21/23 32

ARRAY IMPLEMENTATION

C D ?

frontrear

B C D

front rear

A B

? ?A

data

Bigger Array

? ? ? ? ?

The EnsureCapacity method requires several steps before a new array is created and the elements copies.

Page 33: Queues

04/21/23 33

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.

Page 34: Queues

04/21/23 34

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

}

Page 35: Queues

04/21/23 3504/21/23 35

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

  }

Page 36: Queues

04/21/23 36

The queue after adding element E

Page 37: Queues

04/21/23 37

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?

Page 38: Queues

04/21/23 38

 

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; 

Page 39: Queues

04/21/23 39

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

Page 40: Queues

04/21/23 40

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;

}

Page 41: Queues

04/21/23 41

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.

Page 42: Queues

04/21/23 42

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.

Page 43: Queues

04/21/23 43

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.

Page 44: Queues

04/21/23 44

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

04/21/23 45

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

04/21/23 46

Pseudocode For Arrival

Passengers Arrival: if( new Passenger comes )

{

if( is First Class)

hpQue.enqueue( new Passenger );

else

lpQue.enqueue( new Passenger );

}

Page 47: Queues

04/21/23 47

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

}

Page 48: Queues

04/21/23 48

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

Page 49: Queues

04/21/23 49

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

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

if (capacity < 2)throw new IllegalArgumentException ("Capacity must be > 1");

queue =<T> new Object[capacity];rear = front = 0;

}

Page 50: Queues

04/21/23 50

ArrayQueuePT --- Size()

How many items currently in the queue?

public int size()

{

return count;

}

Page 51: Queues

04/21/23 51

ArrayQueuePT --- isEmpty/isFull

// check whether the queue is empty

public boolean isEmpty()

{

return size() == 0;

}

// check whether the queue is full

public boolean isFull()

{

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

}

Page 52: Queues

04/21/23 52

ArrayQueuePT --- enqueue()

public void enqueue(T item)

{

if (item == null)

throw new IllegalArgumentException ("Item is null");

if (isFull())

ensureCapacity();

queue[rear] = item;

rear = (rear + 1)%queue.length;

}

Page 53: Queues

04/21/23 53

ArrayQueuePT --- dequeue()

public T dequeue( ) {

if (isEmpty())throw new IllegalStateException (“Queue is empty");

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

return frontItem;}

Page 54: Queues

04/21/23 54

ArrayQueuePT peek() Method

public T peek()

{

if (isEmpty())

throw new IllegalStateException (“Queue is empty");

return queue[front];

}

Page 55: Queues

04/21/23 55

Interface

Users don’t need to know how Queue is implemented.

Users 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

insert, dequeue(), peek, isFull, isEmpty

Page 56: Queues

04/21/23 56

Interface for Queue

public interface QueuePT<T>

{

public boolean isEmpty();

public boolean isFull();

public T peek();

public T dequeue();

public void enqueue(T item);

public int size();

}

Page 57: Queues

04/21/23 57

Implementation of ArrayQueuePT Class

public class ArrayQueuePT<T> implements QueuePT<T>

{

private final static int DEFAULT_CAPACITY = 100;

private T queue[]; // The array holds the queue

private int rear, front;

// index of rear, front items in queue

Page 58: Queues

04/21/23 58

Create an object of ArrayQueuePT

// create a queue with default capacity

QueuePT<T> myqueue = new ArrayQueuePT<T>();

// create a queue with 1024 elements

QueuePT<T> queue = new ArrayQueuePT<T>(1024);

Page 59: Queues

04/21/23 59

The operations on a queue

Page 60: Queues

04/21/23 60

The QueueADT interface in UML

Page 61: Queues

04/21/23 61

Coded Messages

Let's use a queue to help us encode and decode messages

A Caesar cipher encodes a message by shifting each letter in a message by a constant amount k

If k is 5, A becomes F, B becomes G, etc.

However, this is fairly easy to break

An improvement can be made by changing how much a letter is shifted depending on where the letter is in the message

Page 62: Queues

04/21/23 62

Coded Messages

A repeating key is a series of integers that determine how much each character is shifted

For example, consider the repeating key

3 1 7 4 2 5

The first character in the message is shifted 3, the next 1, the next 7, and so on

When the key is exhausted, we just start over at the beginning of the key

Page 63: Queues

04/21/23 63

An encoded message using a repeating key

Page 64: Queues

04/21/23 64

Coded Messages

We'll use a queue to store the values of the key

We'll dequeue a value when needed

After using a key value, we then enqueue it back onto the end of the queue

That way the queue represents the constantly cycling values in the key

See Codes.java (page 183)

Page 65: Queues

04/21/23 65

Listing 7.2

Page 66: Queues

04/21/23 66

Listing 7.2 (cont.)

Page 67: Queues

04/21/23 67

UML description of Codes program

Page 68: Queues

04/21/23 68

Printing Job Management

4 documents are ready to print

Print the printer status

When a new document comes

which document is finished

Using ArrayQueuePT

Page 69: Queues

04/21/23 69

New Printing Jobs come

public void printstatus() { QueuePT que = new ArrayQueuePT( ); //Create a newqueue 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 70: Queues

04/21/23 70

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

}