Presentation is loading. Please wait.

Presentation is loading. Please wait.

5/4/20151 Queues Implementations. 5/4/20152 Outline Queues Basic operations Examples of useImplementations Array-based and linked list-based.

Similar presentations


Presentation on theme: "5/4/20151 Queues Implementations. 5/4/20152 Outline Queues Basic operations Examples of useImplementations Array-based and linked list-based."— Presentation transcript:

1 5/4/20151 Queues Implementations

2 5/4/20152 Outline Queues Basic operations Examples of useImplementations Array-based and linked list-based

3 5/4/20153 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 vehicles at toll booth ticket line at movies Airport Security Check

4 5/4/20154 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 Output Input

5 5/4/20155 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 -. queue(Buffered) Kept in queue(Buffered) until the operating system can deal with them.

6 5/4/20156 Examples Queue is a British word for line. Expect O ( 1 ) 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.

7 5/4/20157 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. simulations e.g. 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.

8 5/4/20158 Abstract Data Types Queue Operating on both ends: Operations: EnQueue( insert at rear) DeQueue(remove from front) front rear enqueue dequeue ABC

9 5/4/20159 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

10 5/4/201510 Printing Queue ABC Now printing A.doc BC A.doc is finished. Now printing B.doc BC Now still printing B.doc D.doc comes D A.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

11 5/4/201511 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)

12 5/4/201512 Implementing a Queue Class LinkedList Implement as a LinkedList insertions and deletions from either end are efficient, constant O(1) time good choice good choice ArrayList Implement as an ArrayList Not as simple Not as simple adding values at one end, removing at other end requires multiple shifts Need to use a circular array

13 5/4/201513 Implementing a Queue Class with a linked list Build a Queue from scratch build a linked structure to store the queue elements Attributes required Head A handle for the head node - Head Tail handle for tail node - Tail count integer to store number of values in the queue - count use LinearNode class

14 5/4/201514 Queue Structure Head Size Tail n aQueue... value 0 value 1 value n-1

15 5/4/201515 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

16 5/4/201516 The QueueADT interface in UML

17 5/4/201517 Listing 7.1 Interface

18 5/4/201518 EnsureCapacity Invariant of the Queue ADT (Array version): Ê The number of items is stored in the instance variablesize. Ê The number of items is stored in the instance variable size. non-empty queue Ë For a non-empty queue Ë the items are stored in a circular array beginning at Ë data[front]data[rear]. Ë data[front] and continuing to data[rear]. size is zero and Ì For an empty queue, size is zero and Ì data is a reference to an array, front and rear Ì but no reference is kept to front and rear

19 5/4/201519 Abstract Data Type - Use An Array Using an array to store the elements: Same as Stack class, we use the T dat a type Arrayqueue Use an Arrayqueue, which stores all items that come in. create an array of type T called “que” T que[ ]; create an array of type T called “que”

20 5/4/201520 Queues: Simple Idea _ ARRAYS Store items in an array with : front item index zero front item at index zero last item index rear. last item at index rear. add items at one end of a queue 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 1. increment rear by one and 2.store the new item in data[rear]. 2.store the new item in data[rear].

21 5/4/201521 Two Solutions – DeQUEUE -Array BA …… C 1032 rear=3 front=0 CB …… 1032 rear=2 front=0 A leaves A leavesB and C moved up! When A leaves, B and C have to be moved up! What is wrong with this solution? … Keeping the front item at index 0 1. Keeping the front item at index 0

22 DEQUEUE dequeue,we retrieve data[front]. To dequeue, we retrieve data[front]. inefficientall elements have to be shifted up one place. Dequeue is inefficient: all elements have to be shifted up one place. dequeue will be O( N ). Result: dequeue will be O( N ). Can we do it a more efficient way? 5/4/201522

23 5/4/201523 Better Idea - Increment Front Front Keep a Front index. Dequeue, front. To Dequeue, increment front. abcd Rear abcd Front Rear Now have Big(1) for removal. Can you see another problem that might arise?

24 5/4/201524 Array Implementation of Queue A A BCD Max_Size rear front After A leaves, FRONT MOVE TO B BCD Max_Size rear front 12 3 0 23 n-1 01

25 5/4/201525 Circular Implementation This implementation is O( 1 ) per operation. The problem is after many removals there are many empty places in the front of array but we will quickly reach the end of the array.

26 ARRAY NOT FULL It is possible after Array.length enqueues, we are full, even if the queue is not really full It has many empty spots in the front of array 5/4/201526

27 SOLUTION wraparound Use wraparound to reuse the cells at the start of the array. increment, add one To increment, add one, goes past end, but if rear goes past end, reset rear to zero mod operator. reset rear to zero using the mod operator. Rear can now use empty places at the beginning of the array 5/4/201527

28 5/4/201528 Circular Example - Array Both Front and Rear wraparound as needed. Both Front and Rear wraparound as needed. bcd bcd FrontRear ef efg Front Rear So it is possible for rear to be behind Front!

29 5/4/201529 Circular Array Wrapped around array … … ABC 23n-101 rear=3 front=0 A B C 0 2 3 n-1 1 rear=3 front=0

30 5/4/201530 EnQueue & DeQueue In Circular Array EnQueue rear = (rear + 1) MOD n What is(3 + 1) MOD n = 15 ? A B C 0 2 3 n-1 1 rear=3 DeQueueDeQueue front = (front + 1) MOD n What is(1 + 1) MOD 15 ? B C 0 2 3 n-1 1 front=1 front=0

31 5/4/201531 Empty/Full In Circular Array What is(3 + 1) MOD, n = 15 ? Or 4 mod 15 = 4 rear equals front, Queue is empty When rear equals front, Queue is empty (rear + 1) MOD n equals front, Queue is full When (rear + 1) MOD n equals front, Queue is full Circular array with capacity n at most can hold n-1 items starting at index 0. n-1 items starting at index 0.

32 5/4/201532 Java Implementation- Array Mostly straightforward; maintain: Front Front Rear Rear Current number of items in queue Current number of items in queue array doubling Only tricky part is array doubling because contiguity of wraparound must be maintained.

33 5/4/201533 Implemention of EnsureCapacity Front behind Rear If front is behind rear, and rear is at the end of the array array is full so a new array is allocated the 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.arraycopy ( copyfrom, start, copyto, start, #of items)

34 size is non-zero rear is behind front, If size is non-zero and rear is behind front, a new array is allocated. data[front] to the end are copied The items from data[front] to the end are copied data[0] to data[rear] followed by the items from data[0] to data[rear]. to System.arraycopy() Two separate calls to System.arraycopy() are activated. 5/4/201534 System.ArrayCopy(…………)

35 5/4/201535 Front greater than rear – array full CD? fron front rear BCD frontrear AB ??A data Bigger Array ????? The EnsureCapacity method requires several steps before a new array is created and the elements copies.

36 5/4/201536 Linked List Implementation LinkedQueue The class LinkedQueue has the following invariant: Size Size -The number of items in the queue The items are stored in linked list with front at the head node rear at the final node. front at the head node and rear at the final node. front is the head reference The instance variable front is the head reference and rear is the tail reference. front and rear are null. For the empty queue, both front and rear are null.

37 5/4/201537 Code for Enqueue - LinkedQUEUE rear and front must be null: In the case of the empty list, both rear and front must be null: LinearNode node = new LinearNode (item, null); if( isEmpty()) { // insert first item // same as insertFirst { // insert first item // same as insertFirst front = node; front = node; rear = front; } else { // not empty, add to end (InsertTail) rear.next=node; or rear = node rear = rear.next;// or rear = node }

38 5/4/201538 The queue after adding element E

39 5/4/2015395/4/201539 Dequeue Code for Dequeue //* Remove the first object from the queue - same as removeFirst public T dequeue() throws EmptyQueueException { // throw an exception if( isEmpty()) // throw an exception else else // 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; }

40 5/4/201540 Customer Service In Fleet Bank Suppose there is only one customer service available in Fleet Bank in Saturday morning every 3 minutes In every 3 minutes, a new customer arrives at the end of waiting line 5 minutes for the service Each customer will need 5 minutes for the service first 30 minutes Print out the information after the first 30 minutes What variables do we need? The time of arrival and departure for each customer The 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?

41 5/4/201541 public class BankServiceQueue { //Create a new queue QueuePT que = new ArrayQueuePT (100); QueuePT que = new ArrayQueuePT (100); // method runs until timed out public void run() public void run() { // instance variables // instance variables // time at start int time = 0; // time at start // number of customers int incustomer = 0; // number of customers // time to process a customer int servicetime = 0; // time to process a customer

42 5/4/201542 Customer In Service // what's going on in 30 minutes while ( time <= 30 ) { // if queue is not empty, one customer service is started // customer leaves when finished - service time is 5 minutes if( servicetime == 5 ) if( servicetime == 5 ) { dequeue dequeue start another job start another job } }

43 5/4/201543 New Customer Comes // in every 3 minutes, there is a new customer coming. if( time%3==0 ) { // enqueue a customer // print out service and start all over again // print out service and start all over again } time = time + 1; }

44 5/4/201544 Priority Queues where queues store tasks to be performed by the CPUmore important than others. In an operating system where queues store tasks to be performed by the CPU, some jobs are more important than others. answering a system call vs. printing a file. E. G. answering a system call vs. printing a file. Priorities are assigned to the jobs. A Priority Queue stores not only the item but its priority.

45 Dequeue Jobs are dequeued according to their priority and jobs with the same priority are dequeued according to which entered first. 5/4/201545

46 5/4/201546 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.

47 5/4/201547 Priority Queue --- Air Travel Only one check-in service in United Airline at airport Two waiting lines for passengers one is First class service one is First class service the other is Economy class service the other is Economy class service Passengers in the first-class waiting line have higher priority They check in before the economy-class waiting line.

48 5/4/201548 Priority Queue Two queues high priority queue one is high priority queue low priority queue the other is low priority queue Service rules: First serve the people in high priority queue First serve the people in high priority queue If no passengers are in high priority queue, serve the passengers in low priority queue If no passengers are in high priority queue, serve the passengers in low priority queue

49 5/4/201549 Two Queues High Priority Queue, will come in hpQue Low Priority Queue, will come in lpQue DCH Check In GFEBA High Priority Queue Low Priority Queue Customers coming in

50 5/4/201550 Pseudocode For Arrival Passengers Arrival: if( new Passenger comes ) { if( is First Class) hpQue.enqueue( new Passenger ); else lpQue.enqueue( new Passenger ); }

51 5/4/201551 Pseudocode For Service Priority Service: if( hpQue is not empty ) // high priority queue is not empty { // high priority queue is not empty high priority serve the passenger from high priority queue, hpQue.dequeue(); } else { // high priority queue is empty low priority serve the passenger from low priority queue, lpQue.dequeue(); }

52 5/4/201552 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; }

53 5/4/201553 ArrayQueuePT - TWO Constructors // Creates a queue with the default capacity public ArrayQueuePT () { 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 = new Object[capacity]; // create array of T rear = front = 0; rear = front = 0; } }

54 5/4/201554 ArrayQueuePT --- isEmpty/isFull // check whether the queue is empty public boolean isEmpty() { return size() == 0; } check whether the queue is full // check whether the queue is full public boolean isFull() { return size() == queue.length-1; }

55 5/4/201555 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;// wraps around }

56 5/4/201556 ArrayQueuePT --- 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 wraps around at end of queue front = (front + 1) % queue.length; // front wraps around at end of queue return frontItem; }

57 5/4/201557 ArrayQueuePT peek() Method public T peek() { if (isEmpty()) throw new IllegalStateException (“Queue is empty"); return queue[front]; }

58 5/4/201558 Interface Users don’t need to know how the Queue is implemented: An array or a linked list how they can operate the Queue. 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

59 5/4/201559 Interface for Queue public interface QueuePT { public boolean isEmpty(); public boolean isFull(); public T peek(); public T dequeue(); public void enqueue(T item); public int size(); }

60 5/4/201560 Create an object of ArrayQueuePT QueuePT is the interface for ArrayQueue // create a queue with default capacity QueuePT myqueue = new ArrayQueuePT (); // create a queue with 1024 elements QueuePT queue = new ArrayQueuePT (1024);

61 5/4/201561 The operations on a queue

62 5/4/201562 Coded Messages encode and decode messages Let's use a queue to help us encode and decode messages Caesar cipher shifting each letter in a message by a constant amount k A Caesar cipher encodes a message by shifting each letter in a message by a constant amount k k is 5, If k is 5, A becomes F, B becomes G, C become Hetc. easy to break However, this is fairly easy to break

63 5/4/201563 Coded Messages Instead, change how much a letter is shifted depending on where the letter is in the message repeating key is a series of integers that determine how much each character is shifted A repeating key is a series of integers that determine how much each character is shifted

64 Repeating Key repeating key For example, consider the repeating key 3 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 we just start over at the beginning of the key When the key is exhausted, we just start over at the beginning of the key 5/4/201564

65 5/4/201565 An encoded message using a repeating key So k was moved up three places to N to O N was moved up one place to O O 7 places to v etc. O was moved up 7 places to v etc. Notice that e becomes a j and an l

66 5/4/201566 Coded Messages queue to store the values of the key We'll use a queue to store the values of the key dequeue a value when needed We'll dequeue a value when needed we then enqueue it back onto the end of the queue After using a key value, we then enqueue it back onto the end of the queue constantly cycling values in the key That way the queue represents the constantly cycling values in the key See Codes.javaCodes.java

67 5/4/201567 Listing 7.2

68 5/4/201568 Listing 7.2 (cont.)

69 5/4/201569 UML description of Codes program


Download ppt "5/4/20151 Queues Implementations. 5/4/20152 Outline Queues Basic operations Examples of useImplementations Array-based and linked list-based."

Similar presentations


Ads by Google