Title: Queues
1Queues
2Outline
- Queues
- Basic operations
- Examples of use
- Implementations
- Array-based and linked list-based
3Building 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
4Queue
- 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
5Queues 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.
6More Examples of Queue
- In our daily life
- Airport Security Check
- Cinema Ticket Office
- Bank, ATM
7Examples
- 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.
8Applications
- 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.
9Abstract Data Types
- Queue
- Operating on both ends
- Operations EnQueue(in), DeQueue(out)
enqueue
dequeue
A
B
C
front
rear
10Printing 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
11Printing Queue
- A.doc B.doc C.doc arrive to printer.
Now printing A.doc
A
B
C
B
C
A.doc is finished. Now printing B.doc
D.doc comes
B
C
Now still printing B.doc
D
C
D
B.doc is finished. Now printing C.doc
D
C.doc is finished. Now printing D.doc
12First-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.
13Implementing 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
14Implementing 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
15Queue Structure
Head Size Tail
aQueue
n
. . .
. . .
value0
value1
valuen-1
16Operations
- 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
17The QueueADT interface in UML
18Listing 7.1 Interface
19Abstract 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.
20Queues 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 datarear. - To get the next item, we retrieve datafront.
Dequeue is inefficient all elements have to be
shifted up one place. - Result Dequeue will be O( N ).
21Two Solutions
- Shifting all items to front in the array when
dequeue operation. ( Too Costly )
A leaves
1
0
n-1
3
2
1
0
n-1
3
2
B
A
C
C
B
rear3
front0
rear2
front0
22Better Idea
- Keep a Front index.
- To Dequeue, increment front.
Front
Front
Rear
Front
23Array Implementation of Queue
1
0
n-1
3
2
B
A
D
C
rear
front
Max_Size
After A leaves,
1
0
n-1
3
2
B
D
C
rear
front
Max_Size
24Circular 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.
25Circular Example - Array
- Both Front and Rear wraparound as needed.
Rear
Front
b
c
d
e
f
Front
Rear
b
c
d
e
f
g
26Circular Array
rear3
3
2
C
1
front0
1
0
n-1
3
2
B
B
A
C
A
0
n-1
rear3
front0
27EnQueue DeQueue In Circular Array
- DeQueue
- front (front 1) MOD n
- EnQueue
- rear (rear 1) MOD n
rear3
front1
3
3
2
2
C
C
1
1
B
B
A
0
0
n-1
n-1
28Empty/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.
29Java 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.
30EnsureCapacity
- 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 datafront and
continuing to datarear. - For an empty queue, size is zero and data is a
reference to an array, but no reference is kept
to front and rear
31Implemention of EnsureCapacity
- If size is non-zero, and front is less than rear,
then a new array is allocated and the data from
datafront to datarear is copied using
System.arraycopy. - If size is non-zero and front is greater rear, a
new array is allocated . - The items from datafront to the end are copied
followed by the items from data0 to datarear.
Two separate calls to System.arraycopy are
activated.
32ARRAY IMPLEMENTATION
front
rear
The EnsureCapacity method requires several steps
before a new array is created and the elements
copies.
C
D
?
A
B
data
B
C
D
?
?
A
?
?
?
?
?
front
rear
Bigger Array
33Linked 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.
34Code for Enqueue
- In the case of the empty list, both rear and
front must be null - LinearNodeltTgt node new LinearNodeltTgt(item,
null) - if( isEmpty())
- // insert first item
- front node
- rear front
-
- else // insert item that is not first,
add to end - rear.nextnode
- rear rear.next// or rear node
-
35Code 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
-
-
-
9/11/2015
35
36The queue after adding element E
37Customer 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?
38-
- public class BankServiceQueue
-
-
- public void run()
-
- //Create a new queue
- QueuePTltTgt que new ArrayQueuePTltTgt(100)
- int time 0
- int incustomer 0
- int servicetime 0
-
-
39Customer In Service
- // what's going on in 30 minutes
- while ( time lt 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
-
-
40New Customer Comes
- // in every 3 minutes, there is a new customer
coming. - if( time30 )
-
- // enqueue a customer
- // print it out and start all over again
-
- time time 1
41Priority 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.
42Priority 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.
43Priority 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.
44Priority 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
45Two Queues
- High Priority Queue, will come in hpQue
- Low Priority Queue, will come in lpQue
High Priority Queue
Check In
Customers coming in
D
C
H
G
F
E
B
A
Low Priority Queue
46Pseudocode For Arrival
- Passengers Arrival
- if( new Passenger comes )
-
- if( is First Class)
- hpQue.enqueue( new Passenger )
- else
- lpQue.enqueue( new Passenger )
-
47Pseudocode 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()
-
48Implementation 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
49ArrayQueuePT Constructor
- // Creates a queue with the default capacity
- public ArrayQueuePTltTgt ()
-
- this(DEFAULT_CAPACITY) // creates this queue
with the default capacity -
- // Creates a queue with a user-specified capacity
- public ArrayQueuePT (int capacity)
-
- if (capacity lt 2)
- throw new IllegalArgumentException ("Capacity
must be gt 1") - queue ltTgt new Objectcapacity
- rear front 0
50ArrayQueuePT --- Size()
- How many items currently in the queue?
- public int size()
-
- return count
-
51ArrayQueuePT --- 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
52ArrayQueuePT --- enqueue()
- public void enqueue(T item)
-
- if (item null)
- throw new IllegalArgumentException ("Item is
null") - if (isFull())
- ensureCapacity()
- queuerear item
- rear (rear 1)queue.length
53ArrayQueuePT --- dequeue()
- public T dequeue( )
-
- if (isEmpty())
- throw new IllegalStateException (Queue is
empty") - T frontItem queuefront
-
- queuefront null
-
- front (front 1)queue.length
- return frontItem
54ArrayQueuePT peek() Method
- public T peek()
-
- if (isEmpty())
- throw new IllegalStateException (Queue is
empty") - return queuefront
55Interface
- Users dont 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
56Interface for Queue
- public interface QueuePTltTgt
-
- public boolean isEmpty()
- public boolean isFull()
- public T peek()
- public T dequeue()
- public void enqueue(T item)
- public int size()
57Implementation of ArrayQueuePT Class
- public class ArrayQueuePTltTgt implements
QueuePTltTgt -
- 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
58Create an object of ArrayQueuePT
- // create a queue with default capacity
- QueuePTltTgt myqueue new ArrayQueuePTltTgt()
- // create a queue with 1024 elements
- QueuePTltTgt queue new ArrayQueuePTltTgt(1024)
59The operations on a queue
60The QueueADT interface in UML
61Coded 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
62Coded 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
63An encoded message using a repeating key
64Coded 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)
65Listing 7.2
66Listing 7.2 (cont.)
67 UML description of Codes program
68Printing Job Management
- 4 documents are ready to print
- Print the printer status
- When a new document comes
- which document is finished
- Using ArrayQueuePT
69New 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" )
70Finishing 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")