Presentation is loading. Please wait.

Presentation is loading. Please wait.

Queues Implementations 6/17/2018.

Similar presentations


Presentation on theme: "Queues Implementations 6/17/2018."— Presentation transcript:

1 Queues Implementations 6/17/2018

2 Outline Queues Basic operations Examples of use Implementations
Array-based and linked list-based 6/17/2018

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 6/17/2018

4 Queue Output Input Queue: First In First Out (FIFO) Toll Station
Car comes, pays, leaves Check-out in Big Y market Customer comes, checks out and leaves A B C D Output Input 6/17/2018

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. 6/17/2018

6 More Examples of Queue Airport Security Check Cinema Ticket Office
In our daily life Airport Security Check Cinema Ticket Office Bank, ATM 6/17/2018

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. 6/17/2018

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. 6/17/2018

9 Abstract Data Types enqueue dequeue rear front Queue
Operating on both ends Operations: EnQueue(in), DeQueue(out) enqueue dequeue C B A rear front 6/17/2018

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 6/17/2018

11 Printing Queue A.doc B.doc C.doc arrive to printer. Now printing A.doc
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 6/17/2018

12 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. 6/17/2018

13 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 6/17/2018

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 6/17/2018

15 Queue Structure aQueue . . . value0 value1 . . . valuen-1
Head Size Tail n . . . value0 value1 . . . valuen-1 6/17/2018

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 6/17/2018

17 The QueueADT interface in UML
6/17/2018

18 Listing 7.1 Interface 6/17/2018

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. 6/17/2018

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 ). 6/17/2018

21 Two Solutions Shifting all items to front in the array when dequeue operation. ( Too Costly… ) A leaves n-1 3 2 1 n-1 3 2 1 C B A C B rear=3 front=0 rear=2 front=0 6/17/2018

22 Better Idea Keep a Front index. To Dequeue, increment front. Front
Rear a b c d Rear Front 6/17/2018

23 Array Implementation of Queue
3 2 1 D C B A rear front Max_Size After A leaves, n-1 3 2 1 D C B rear front Max_Size 6/17/2018

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. 6/17/2018

25 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 6/17/2018

26 Circular Array Wrapped around array rear=3 3 2 C front=0 1 B … … C B A
B C B A A n-1 rear=3 front=0 6/17/2018

27 EnQueue & DeQueue In Circular Array
front = (front + 1) MOD n EnQueue rear = (rear + 1) MOD n rear=3 front=1 3 3 2 2 C C 1 1 B B A n-1 n-1 6/17/2018

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. 6/17/2018

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. 6/17/2018

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 6/17/2018

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. 6/17/2018

32 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 6/17/2018

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. 6/17/2018

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 6/17/2018

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; 6/17/2018 6/17/2018 35

36 The queue after adding element E
6/17/2018

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? 6/17/2018

38 public class BankServiceQueue { public void run() //Create a new queue
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; 6/17/2018

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 } 6/17/2018

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; 6/17/2018

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. 6/17/2018

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. 6/17/2018

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. 6/17/2018

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 6/17/2018

45 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 6/17/2018

46 Pseudocode For Arrival
Passengers Arrival: if( new Passenger comes ) { if( is First Class) hpQue.enqueue( new Passenger ); else lpQue.enqueue( new Passenger ); } 6/17/2018

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(); 6/17/2018

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; } 6/17/2018

49 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; 6/17/2018

50 ArrayQueuePT --- Size()
How many items currently in the queue? public int size() { return count; } 6/17/2018

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; 6/17/2018

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; } 6/17/2018

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; } 6/17/2018

54 ArrayQueuePT peek() Method
public T peek() { if (isEmpty()) throw new IllegalStateException (“Queue is empty"); return queue[front]; } 6/17/2018

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 6/17/2018

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(); } 6/17/2018

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 6/17/2018

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); 6/17/2018

59 The operations on a queue
6/17/2018

60 The QueueADT interface in UML
6/17/2018

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 6/17/2018

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 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 6/17/2018

63 An encoded message using a repeating key
6/17/2018

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) 6/17/2018

65 Listing 7.2 6/17/2018

66 Listing 7.2 (cont.) 6/17/2018

67 UML description of Codes program
6/17/2018

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 6/17/2018

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" ); 6/17/2018

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"); } 6/17/2018


Download ppt "Queues Implementations 6/17/2018."

Similar presentations


Ads by Google