queues n.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
Queues PowerPoint Presentation
Download Presentation
Queues

Loading in 2 Seconds...

play fullscreen
1 / 70

Queues - PowerPoint PPT Presentation


  • 3622 Views
  • Uploaded on

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

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about 'Queues' - Ava


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
queues

Queues

Implementations

outline
Outline
  • Queues
    • Basic operations
    • Examples of use
  • Implementations
    • Array-based and linked list-based
building a queue class
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
queue

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
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
More Examples of Queue
  • In our daily life
    • Airport Security Check
    • Cinema Ticket Office
    • Bank, ATM
examples
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
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
Abstract Data Types
  • Queue
    • Operating on both ends
    • Operations: EnQueue(in),DeQueue(out)

enqueue

dequeue

C

B

A

front

rear

printing job management
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
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
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
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 queue class1
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
queue structure
QueueStructure

aQueue

Head Size Tail

n

. . .

value0

value1

. . .

valuen-1

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

better idea

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

}

slide35

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
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?
slide38
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
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
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
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
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
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
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
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
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
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
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
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
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;

}

arrayqueuept isempty isfull
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;

}

arrayqueuept enqueue
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;

}

arrayqueuept dequeue
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;

}

arrayqueuept peek method
ArrayQueuePT peek() Method

public T peek()

{

if (isEmpty())

throw new IllegalStateException (“Queue is empty");

return queue[front];

}

interface
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
interface for queue
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();

}

implementation of arrayqueuept class
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

create an object of arrayqueuept
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);

coded messages
Coded Messages
  • Let's use a queue to help us encode and decode messages
  • A Caesar cipherencodes 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
coded messages1
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
coded messages2
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)
printing job management1
Printing Job Management
  • 4 documents are ready to print
  • Print the printer status
    • When a new document comes
    • which document is finished
  • Using ArrayQueuePT
new printing jobs come
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" );

finishing printing jobs
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");

}