Upload
neal-hewlett
View
225
Download
3
Tags:
Embed Size (px)
Citation preview
04/18/23 2
Outline
QueuesQueues Basic operations Examples of use
ImplementationsImplementations Array-based and linked list-based
04/18/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 queuesExamples of queues vehicles at toll booth ticket line at movies Airport Security Check
04/18/23 4
Queue First In First Out (FIFO)
Queue: 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
04/18/23 5
Queues in a Computer System
When a process (program) requires a certain resource
Printer - printing jobs put in a queue. First in, first out
Characters entered in a keyboard - .
Kept in queue(Buffered) queue(Buffered)
until the operating system can deal with them.
04/18/23 6
Examples
Queue is a British word for line.
Expect Expect O O ( 1 ) ( 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.
04/18/23 7
Applications
Queues are also useful for storing pending work: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. simulations e.g.
Simulating traffic at an intersection by creating a growing line of automobiles waiting for the light to change.
04/18/23 8
Abstract Data Types
Queue Operating on both ends: Operations: EnQueue( insert at rear) DeQueue(remove from front)
frontfrontrearrear
enqueueenqueuedequeuedequeue
ABC
04/18/23 9
Printing Job Management
Many users send their printing jobs to ECS public printer
ECS 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
04/18/23 10
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 at time 1A.doc B.doc C.doc arrive to printer at time 1
CD
D
B.doc is finished. Now printing C.doc
C.doc is finished. Now printing D.doc
04/18/23 11
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 of entry.
When we enqueue entries in the queue and then dequeue them one by one,
we will get the items in the same order of entry.
The first one enqueued is the first one dequeued. (FIFO)
The first one enqueued is the first one dequeued. (FIFO)
04/18/23 12
Implementing a Queue Class
Implement as a LinkedListLinkedList
insertions and deletions from either end are efficient, constant O(1) time
good choicegood choice
Implement as an ArrayListArrayList Not as simple Not as simple adding values at one end, removing at other end
requires multiple shifts Need to use a circular array
04/18/23 13
Implementing a Implementing a Queue Queue Class with a linked listClass with a linked list
Build a Queue from scratch build a linked structure to store the queue elements
Attributes requiredAttributes required A handle for the head node - HeadHead handle for tail node - TailTail integer to store number of values in the queue -
countcount use LinearNode class
04/18/23 15
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
04/18/23 18
EnsureCapacity
Invariant of the Queue ADT (Array version):Invariant of the Queue ADT (Array version):
The number of items is stored in the instance variableThe number of items is stored in the instance variable size size ..
For a non-empty queue non-empty queue
the items are stored in a circular array beginning at data[front]data[front] and continuing to data[rear].data[rear].
For an empty queue, size is zero and size is zero and
data is data is a reference to an array, a reference to an array,
but no reference is kept to front and rearfront and rear
04/18/23 19
Abstract Data Type - Use An Array
Using an array to store the elements:Using an array to store the elements:
Same as Stack class, we use the T datSame as Stack class, we use the T data typea type
Use an ArrayqueueArrayqueue, which stores all items that come in.
T que[ ]; create an array of type T called “que”create an array of type T called “que”
04/18/23 20
Queues: Simple Idea _ ARRAYSQueues: Simple Idea _ ARRAYS
Store items in an array with :
front item front item at index zero index zero last item last item at index index rearrear. .
We will add items add items at one end of a queue at one end of a queue and remove them remove them from the other end.from the other end.
Enqueue is easy: Enqueue is easy:
1. increment increment rear by one and rear by one and 2.store the new item in data[rear]2.store the new item in data[rear]..
04/18/23 21
Two Solutions – DeQUEUE -Array
B A…… C1 03 2
rear=3 front=0
C B……1 03 2
rear=2 front=0
A leaves
When A leavesA leaves, B and C B and C have to be moved up!moved up!
What is wrong with this solution?What is wrong with this solution?
…
1. Keeping the front item at index 0Keeping the front item at index 0
DEQUEUEDEQUEUE
To dequeue,dequeue, we retrieve data[front].we retrieve data[front].
Dequeue is inefficientinefficient: all elements have to be shifted all elements have to be shifted up one place.up one place.
Result: dequeue will be dequeue will be OO( ( NN ). ).
Can we do it a more efficient way?
04/18/23 22
04/18/23 23
Better Idea - Increment Front
Keep a FrontFront index.
To Dequeue,Dequeue, increment frontfront..
a b c d
Rear
a b c d
FrontFront
Front
Rear
Now have Big(1) for removal. Can you see another problem that might arise?
04/18/23 24
Array Implementation of Queue
AA B C D
Max_Sizerearfront
After A leaves, FRONT MOVE TO B After A leaves, FRONT MOVE TO B
B C D
Max_Sizerearfront
1 2 30
2 3 n-10 1
04/18/23 25
Circular Implementation
This implementation is O( 1 ) per operation.
The problem is after many removals there are
many empty places in the front of arraymany empty places in the front of array
but we will quickly reach the end of the array.
ARRAY NOT FULL
It is possible after It is possible after Array.lengthArray.length enqueues, enqueues,
we are full, we are full,
even if the queue is even if the queue is not really full not really full
It has many It has many empty spots empty spots in the front of arrayin the front of array
04/18/23 26
SOLUTION SOLUTION
Use wraparoundwraparound to reuse the cells at the start of the array.
To incrementincrement, add one, add one,
but if rear goes past end, goes past end,
reset rear to zero reset rear to zero using the mod operator.mod operator.
Rear can now use empty places at the beginning of the Rear can now use empty places at the beginning of the arrayarray
04/18/23 27
04/18/23 28
Circular Example - Array
Both Both FrontFront and and RearRear wraparound as needed. wraparound as needed.
b c d
b c d
FrontFrontRearRear
e f
e fg
FrontFront RearRear
So it is possible for rear to be behind Front!So it is possible for rear to be behind Front!
04/18/23 29
Circular Array
Wrapped around array
…… A B C2 3n-1 0 1
rear=3front=0
A
BC
0
23
n-1
1
rear=3
front=0
04/18/23 30
EnQueue & DeQueue In Circular ArrayEnQueue & DeQueue In Circular Array
EnQueueEnQueue rear = (rear + 1) MOD n What is(3 + 1) MOD n = 15 ?
A
BC
0
23
n-1
1
rear=3
• DeQueueDeQueue• front = (front + 1) MOD n• What is(1 + 1) MOD 15 ?
BC
0
23
n-1
1
front=1
front=0
04/18/23 31
Empty/Full In Circular Array
What is(3 + 1) MOD , n = 15 ? Or 4 mod 15 = 4
When rear equals front, Queue is emptyrear equals front, Queue is empty
When (rear + 1) MOD n equals front, Queue is full(rear + 1) MOD n equals front, Queue is full
Circular array with capacityCircular array with capacity nn at most can hold at most can hold
n-1n-1 items starting at index 0. items starting at index 0.
04/18/23 32
Java Implementation- Array
Mostly straightforward; maintain:
FrontFront RearRear Current number of items in queueCurrent number of items in queue
Only tricky part is array doubling array doubling because contiguity of wraparound must be maintained.
04/18/23 33
Implemention of EnsureCapacity Implemention of EnsureCapacity Front behind Rear Front behind Rear
If front is behind rear, and rear is at the end of the arrayIf front is behind rear, and rear is at the end of the array
the array is full so a new array is allocated array is full so a new array is allocated and the
data from data[front] to data[rear] data from data[front] to data[rear] is copied using;
System.arraycopySystem.arraycopy((copyfrom, start, copyto, copyfrom, start, copyto, start, #of items)start, #of items)
If size is size is non-zero non-zero and rear is behind front , rear is behind front ,
a new array is allocated .
The items from data[front] to the end are copied data[front] to the end are copied
followed by the items from data[0] to data[rear]data[0] to data[rear].
Two separate calls to System.arraycopy() to System.arraycopy() are activated.
04/18/23 34
System.ArrayCopy(…………)
04/18/23 35
Front greater than rear – array full
C D ?fronfrontrearrear
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.
04/18/23 36
Linked List Implementation
The class LinkedQueue LinkedQueue has the following invariant:
SizeSize -The number of items in the queue
The items are stored in linked list with
frontfront at the head node at the head node and rearrear at the final node. at the final node.
The instance variable frontfront is the head reference is the head reference and
rear rear is the tail reference.is the tail reference.
For the empty queue, both front and rearfront and rear are null. are null.
04/18/23 37
Code for Enqueue - LinkedQUEUECode for Enqueue - LinkedQUEUE
In the case of the empty list, both rear and frontrear and front must be null: must be null:
LinearNode<T> node = new LinearNode<T>(item, null);LinearNode<T> node = new LinearNode<T>(item, null);
if( isEmpty())if( isEmpty())
{ { // insert first item // same as insertFirst// insert first item // same as insertFirst
front = node;front = node;
rear = front;rear = front;
}}
else { // not empty , add to end (InsertTail)
rear.next=node;
rear = rear.next;// or rear = nodeor rear = node
}
04/18/23 3904/18/23 39
Code for DequeueDequeue
//* Remove the first object from the queue - same as removeFirst//* Remove the first object from the queue - same as removeFirst
public T dequeue() throws EmptyQueueExceptionpublic T dequeue() throws EmptyQueueException {
if( isEmpty()) // throw an exception// throw an exception elseelse // 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; }
04/18/23 40
Customer Service In Fleet Bank
Suppose there is only one customer service available in Fleet Bank in Saturday morning
In every 3 minutesevery 3 minutes, a new customer arrives at the end of waiting line
Each customer will need 5 minutes for the service 5 minutes for the service
Print out the information after the first 30 minutesfirst 30 minutes
What variables do we need?What variables do we need?
The time of arrival and departure for each customerThe time of arrival and departure for each customer How many customers are in the line?How many customers are in the line? Who is the current serving customer?Who is the current serving customer?
04/18/23 41
public class BankServiceQueue {
//Create a new queue//Create a new queue QueuePT<T> que = new ArrayQueuePT<T>(100); QueuePT<T> que = new ArrayQueuePT<T>(100); // method runs until timed out// method runs until timed out public void run()public void run() {{ // instance variables // instance variables int time = 0; // time at start// time at start
int incustomer = 0; // number of customers// number of customers
int servicetime = 0; // time to process a customer// time to process a customer
04/18/23 42
Customer In Service
// what's going on in 30 minutes while ( time <= 30 ) { // if queue is not empty, one customer service is started// if queue is not empty, one customer service is started
// customer leaves when finished - service time is 5 minutes// customer leaves when finished - service time is 5 minutes if( servicetime == 5 ) if( servicetime == 5 ) {{ dequeuedequeue start another jobstart another job }} }
04/18/23 43
New Customer Comes
// in every 3 minutes, there is a new customer coming// in every 3 minutes, there is a new customer coming..
if( time%3==0 )if( time%3==0 )
{
// enqueue a customer// enqueue a customer
// print out service and start all over again// print out service and start all over again
}
time = time + 1;time = time + 1;
}
04/18/23 44
Priority Queues
In an operating system where queues store tasks to be where queues store tasks to be performed by the CPUperformed by the CPU, some jobs are more important more important than others. than others.
E. G. answering a system call vs. printing a file.answering a system call vs. printing a file.
PrioritiesPriorities are assigned to the jobs. are assigned to the jobs.
A Priority Queue stores not only the A Priority Queue stores not only the itemitem but its but its priority.priority.
Dequeue
Jobs are dequeued according to their priority and Jobs are dequeued according to their priority and
jobs with jobs with the same priority are dequeued the same priority are dequeued according to according to which entered first.which entered first.
04/18/23 45
04/18/23 46
Priority Queue ADTPriority Queue ADT
In some operating systems, there are In some operating systems, there are multiple queues multiple queues with different priorities. with different priorities.
An An array of queues array of queues might be used if the number of might be used if the number of priorities is sufficiently small.priorities is sufficiently small.
04/18/23 47
Priority Queue --- Air Travel
Only one check-in service in United Airline at airport
Two waiting lines for passengers one is First class serviceone is First class service the other is Economy class servicethe other is Economy class service
Passengers in the Passengers in the first-classfirst-class waiting line have waiting line have higher higher priority priority
They check in They check in before the economy-class before the economy-class waiting line.waiting line.
04/18/23 48
Priority Queue
Two queuesTwo queues one is high priority queuehigh priority queue
the other is low priority queuelow priority queue
Service rules: First serve the people in high priority queueFirst serve the people in high priority queue
If no passengers are in high priority queue, serve If no passengers are in high priority queue, serve the passengers in low priority queuethe passengers in low priority queue
04/18/23 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
04/18/23 50
Pseudocode For Arrival
Passengers Arrival: if( new Passenger comes )
{
if( is First Class)
hpQue.enqueue( new Passenger );
else
lpQue.enqueue( new Passenger );
}
04/18/23 51
Pseudocode For Service
Priority Service: if( hpQue is not empty )
{ // high priority queue is not empty// high priority queue is not empty
serve the passenger from high priority high priority queue,
hpQue.dequeue();
}
else {
// high priority queue is empty// high priority queue is empty
serve the passenger from low priority low priority queue,
lpQue.dequeue();
}
04/18/23 52
Implementation for QueueImplementation 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; }
04/18/23 53
ArrayQueuePT - TWO ConstructorsArrayQueuePT - TWO Constructors
// 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]; // create array of Tqueue =<T> new Object[capacity]; // create array of T rear = front = 0;rear = front = 0;
} } }
04/18/23 54
ArrayQueuePT --- isEmpty/isFull
// check whether the queue is empty// check whether the queue is empty
public boolean isEmpty() public boolean isEmpty()
{
return size() == 0;
}
// check whether the queue is fullcheck whether the queue is full
public boolean isFull() public boolean isFull()
{{
return size() == queue.length-1;
}
04/18/23 55
ArrayQueuePT --- enqueue()public void enqueue(T item) 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;// wraps aroundrear = (rear + 1) % queue.length;// wraps around
}}
04/18/23 56
ArrayQueuePT --- dequeue()public T dequeue( ) public T dequeue( ) {{
if (isEmpty())throw new IllegalStateException (“Queue is empty");
T frontItem = queue[front]; queue[front] = null;
// increment front front = (front + 1) % queue.length; front = (front + 1) % queue.length; // front wraps around at end of queue// front wraps around at end of queue
return frontItem;}
04/18/23 57
ArrayQueuePT peek() Method
public T peek() public T peek()
{
if (isEmpty())
throw new IllegalStateException (“Queue is empty");
return queue[front];return queue[front];
}
04/18/23 58
Interface
Users don’t need to know how the Queue is implemented:
An array or a linked listAn array or a linked list
Users only need to know how they can operate the how they can operate the Queue.Queue.
There are many ways to implement Queue, but all of them have the same interfaces
insert, dequeue(), peek, isFull, isEmpty
04/18/23 59
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();
}
04/18/23 60
Create an object of ArrayQueuePT
QueuePT is the interface for ArrayQueue
// 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);
04/18/23 62
Coded Messages
Let's use a queue to help us encode and decode encode and decode messagesmessages
A Caesar cipherCaesar cipher encodes a message by shifting each shifting each letter in a message by a constant amount kletter in a message by a constant amount k
If k is 5, k is 5,
A becomes F, B becomes G, C become Hetc.A becomes F, B becomes G, C become Hetc.
However, this is fairly easy to breakeasy to break
04/18/23 63
Coded Messages
Instead, change how much a letter is shifted depending on where the letter is in the message
A repeating keyrepeating key is a series of integers that determine is a series of integers that determine how much each character is shiftedhow much each character is shifted
Repeating Key
For example, consider the repeating keyrepeating key
3 1 7 4 2 53 1 7 4 2 5
The first character in the message is shifted 3 places, the next character is shifted 1,
the next 7, and so on
When the key is exhausted, we just start over at the we just start over at the beginning of the keybeginning of the key
04/18/23 64
04/18/23 65
An encoded message using a repeating key
So kSo k was moved up three places was moved up three places to Nto NN was moved up one place to Oto OO O was moved up 7 places to v etc.7 places to v etc.
Notice that e becomes a j and an lNotice that e becomes a j and an l
04/18/23 66
Coded Messages
We'll use a queue to store the values of the keyqueue to store the values of the key
We'll dequeue a value when neededdequeue a value when needed
After using a key value, we then enqueue it back onto the we then enqueue it back onto the end of the queueend of the queue
That way the queue represents the constantly cycling values constantly cycling values in the keyin the key
See Codes.java