09. queues

41
241-423 ADSA: Queues/9 241-423 Advanced Data Structures and Algorithms Objective implement queues, bounded queues, and priority queues. Explain Radix sort. Semester 1, 2012-2013 9. Queues

Upload: irmaindarto

Post on 24-Oct-2014

48 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: 09. Queues

241-423 ADSA : Queues/9 1

241-423 Advanced Data Structures and Algorithms

• Objective– implement queues, bounded queues, and

priority queues. Explain Radix sort.

Semester 1, 2012-2013

9. Queues

Page 2: 09. Queues

241-423 ADSA : Queues/9 2

Contents

1. The Queue Collection

2. Interview Scheduler

3. Radix Sort

4. A Bounded Queue

5. Priority Queue Collection

Page 3: 09. Queues

241-423 ADSA : Queues/9 3

1. The Queue Collection

• A queue is a list of items, where items can only enter the queue at the back and exit from the front.

• Elements leave a queue in the same order as they enter – a queue has a First-In-First-Out (FIFO) ordering

Page 4: 09. Queues

241-423 ADSA : Queues/9 4

The Queue Interface

interface Queue<T> ds.util boolean isEmpty()

Returns true if this collection contains no elements and false if the collection has at least 1 element.

T peek() Refer to element at the front of the queue. If empty, throws a NoSuchElementException.

continued

Page 5: 09. Queues

241-423 ADSA : Queues/9 5

interface Queue<T> ds.util T pop()

Removes the element at the front of the queue and returns its value. If the queue is empty, throws a NoSuchElementException.

void push(T item) Inserts item at the back of the queue.

int size() Returns the number of elements in this queue

Page 6: 09. Queues

241-423 ADSA : Queues/9 6

public class LinkedQueue<T> implements Queue<T>{ private LinkedList<T> qlist;

public LinkedQueue () { qlist = new LinkedList<T>(); }

/* implementations of isEmpty(), peek(), pop(), push(), size() using qlist */ :

LinkedQueue implements the Queue

interface using the LinkedList class

The LinkedQueue Class

Page 7: 09. Queues

241-423 ADSA : Queues/9 7

pop() has runtimeefficiency O(1)

public T pop(){ if (isEmpty()) throw new NoSuchElementException( "LinkedQueue pop(): queue empty");

// remove and return first element in list return qlist.removeFirst();}

} // end of LinkedQueue class

Page 8: 09. Queues

241-423 ADSA : Queues/9 8

2. Interview Scheduler

• The interview scheduler is a queue of The interview scheduler is a queue of Time24 objects. It outputs a list of the times Time24 objects. It outputs a list of the times and the potential length of each interview. and the potential length of each interview.

Page 9: 09. Queues

241-423 ADSA : Queues/9 9

Execution

(4:30 + 0:30 == 5pm, the end of the day)

Page 10: 09. Queues

241-423 ADSA : Queues/9 10

import java.io.*;import java.util.Scanner;

import ds.util.LinkedQueue;import ds.time.Time24;

public class InterviewScheduler{ public static void main(String[] args) throws IOException { Time24 END_DAY = new Time24(17,00); // read times from "appt.txt" Scanner input = new Scanner( new FileReader("appt.txt") ); :

Page 11: 09. Queues

241-423 ADSA : Queues/9 11

// create a queue for the appointment times LinkedQueue<Time24> apptQ = new LinkedQueue<Time24>(); while (input.hasNext()) { String apptStr = input.nextLine(); // read time apptQ.push( Time24.parseTime(apptStr) ); // add time to queue }

// output the day's appointment schedule System.out.println("Appointment Interview"); :

Page 12: 09. Queues

241-423 ADSA : Queues/9 12

Time24 apptTime, interviewTime; while (!apptQ.isEmpty()) { apptTime = apptQ.pop(); // get next appointment

/* interview time is time to next appointment or to END_DAY */ if (!apptQ.isEmpty()) interviewTime = apptTime.interval( apptQ.peek()); else interviewTime = apptTime.interval(END_DAY); System.out.println(" " + apptTime + " " + interviewTime); } } // end of main()

} // end of InterviewScheduler class

Page 13: 09. Queues

241-423 ADSA : Queues/9 13

3. Radix Sort

• Radix sort uses the Radix sort uses the digitsdigits in each array element in each array element to sort the array.to sort the array.

• The array elements are passed to ten queues The array elements are passed to ten queues (index 0 to 9) using each element's digit as the (index 0 to 9) using each element's digit as the index. index.

• Elements are copied from the queues back to Elements are copied from the queues back to the original array, in partially sorted order. the original array, in partially sorted order.

Page 14: 09. Queues

241-423 ADSA : Queues/9 14

Radix Sort Example• Array: [91, 6, 85, 15, 92, 35, 30, 22, 39]

After Pass 0: [30, 91, 92, 22, 85, 15, 35, 6, 39]

After Pass 1: [6, 15, 22, 30, 35, 39, 85, 91, 92]

use the unitsdigit in each element

(100 digit)

use the tensdigit in each element

(101 digit)

partiallysorted

fullysorted

continued

Page 15: 09. Queues

241-423 ADSA : Queues/9 15

• The i-th pass distributes the array elements The i-th pass distributes the array elements into one of the 10 queues by looking at the into one of the 10 queues by looking at the digit in each element corresponding to the digit in each element corresponding to the power 10power 10ii. . – in pass 0, look at units digit (10in pass 0, look at units digit (1000))– in pass 1, look at tens digit (10in pass 1, look at tens digit (1011))

continued

Page 16: 09. Queues

241-423 ADSA : Queues/9 16

• Radix sort must carry out d passes, one for Radix sort must carry out d passes, one for each digit in the largest elementeach digit in the largest element– e.g. if the largest element is 92, then d = 2 passes;e.g. if the largest element is 92, then d = 2 passes;

if largest is142, then d == 3 passes if largest is142, then d == 3 passes

Page 17: 09. Queues

241-423 ADSA : Queues/9 17

Radix Sort Methodspublic static void radixSort(int[] arr, int radix){ // create a 10 elem LinkedQueue array LinkedQueue[] digitQueues = new LinkedQueue[10];

// initialize digitQueues to hold empty queues for (i=0; i < digitQueues.length; i++)

digitQueues[i] = new LinkedQueue(); // current digit found by dividing by power int power = 1; // will increase in 10's

for (int i=0; i < radix; i++) { distribute(arr, digitQueues, power); collect(digitQueues, arr); power *= 10; }}

Page 18: 09. Queues

241-423 ADSA : Queues/9 18

private static void distribute(int[] arr, LinkedQueue[] digitQueues, int power)// distribute array elements between 10 queues{ for (int i = 0; i < arr.length; i++) { int digit = (arr[i] / power) % 10; // get digit from element digitQueues[digit].push( arr[i] ); /* use digit to decide which queue should hold the element */ }}

Page 19: 09. Queues

241-423 ADSA : Queues/9 19

private static void collect(LinkedQueue[] digitQueues, int[] arr)// copy elements from the queues back to the array{ int i = 0; // scan the array of queues for (int digit = 0; digit < 10; digit++) while (!digitQueues[digit].isEmpty()) { arr[i] = digitQueues[digit].pop(); // queue-->arr i++; }}

Page 20: 09. Queues

241-423 ADSA : Queues/9 20

import java.util.Random;import ds.util.Arrays;

public class UseRadixSort{ public static void main(String[] args) { int[] arr = new int[50]; // 50-element array

Random rnd = new Random(); for (int i = 0; i < 50; i++) arr[i] = rnd.nextInt(100000); // random nos: 0 to 99999

Arrays.radixSort(arr, 5); // 5 digits in 99999 displayArray(arr); } // end of main()

Using Radix Sort

Page 21: 09. Queues

241-423 ADSA : Queues/9 21

private static void displayArray(int[] arr) { for (int i = 0; i < arr.length; i++) { String s = String.valueOf(arr[i]); // int --> string

// right justify s inside 8 char positions String just = ""; for (int j=0; j < 8-s.length(); j++) just += " "; just += s; System.out.print(just); if ((i+1) % 6 == 0) // newline every 6 numbers System.out.println(); } System.out.println(); } // end of displayArray()

} // end of UseRadixSort

Page 22: 09. Queues

241-423 ADSA : Queues/9 22

Execution

Page 23: 09. Queues

241-423 ADSA : Queues/9 23

Radix Sort Efficiency

• The runtime efficiency of radixSort() is O(radix*n) where the list has n elements and the biggest element has radix digits– a fast linear sorting algorithm

• But radixSort() uses a lot of memory– it needs one queue for each digit

• If we are sorting strings, then we will need 1 queue for each different letter (62+ queues)

Page 24: 09. Queues

241-423 ADSA : Queues/9 24

4. A Bounded Queue

• A bounded queue is a queue that has a A bounded queue is a queue that has a maximum size (capacity). maximum size (capacity).

• A queue insertion can only occur when the A queue insertion can only occur when the queue is not full. queue is not full.

Page 25: 09. Queues

241-423 ADSA : Queues/9 25

• The BQueue class represents a bounded The BQueue class represents a bounded queue. queue.

• The class implements the Queue interface The class implements the Queue interface using an array to store the elementsusing an array to store the elements– an array is okay since the bounded queue has a an array is okay since the bounded queue has a

maximum capacity maximum capacity

The BQueue Class

Page 26: 09. Queues

241-423 ADSA : Queues/9 26

BQueue Class API

interface BQueue<T> implements Queue ds.util BQueue()

Creates a queue with fixed size 50.

BQueue(int size) Creates a queue with specified fixed size.

boolean full() Returns true if the number of elements in the queue equals is fixed size and false otherwise.

and the other methods in the Queue interface

Page 27: 09. Queues

241-423 ADSA : Queues/9 27

// declare an empty bounded queue with capacity 15BQueue<Integer> q = new BQueue<Integer>(15);

for (int i=1; !q.full(); i++) // fill the queueq.push(i);

// print element at the q front, and queue sizeSystem.out.println(q.peek() + ", " + q.size());

try {q.push(40); // try to add 40 to full bqueue

}catch (IndexOutOfBoundsException e){ System.out.println(e); }

BQueue Class Example

1, 15java.lang.IndexOutOfBoundsException: BQueue push(): queue full

Page 28: 09. Queues

241-423 ADSA : Queues/9 28

BQueue Classpublic class BQueue<T> implements Queue<T>{ private T[] queueArray; // array for queue elements

// index of front and back of queue private int qfront, qback;

// queue capacity, and current size private int qcapacity, qcount;

public BQueue(int size) // create an empty bounded queue with the specified size { queueArray = (T[])new Object[size]; qfront = 0; qback = 0; qcapacity = size; qcount = 0; }

Page 29: 09. Queues

241-423 ADSA : Queues/9 29

public BQueue() // a bounded queue of max size 50 { BQueue(50); }

// method full() and other methods in the Queue interface } // end of BQueue class

Page 30: 09. Queues

241-423 ADSA : Queues/9 30

BQueue Class Implementation

No room for E.Need a way to usethe slots at indices 0, 1.

continued

Page 31: 09. Queues

241-423 ADSA : Queues/9 31

• Think of the queue as a circular sequence.

• Element are added in a clockwise order. – the element at index qfront exits the queue

– an element enters the queue at index qback.

continued

Page 32: 09. Queues

241-423 ADSA : Queues/9 32

• qfront and qback 'cycle back' to the front of the array when they move off the end of the array.

Move qback forward: qback = (qback + 1) % qcapacity;Move qfront forward: qfront = (qfront + 1) % qcapacity;

Page 33: 09. Queues

241-423 ADSA : Queues/9 33

Testing if the bQueue is Full

• The bqueue is full when every box of the array The bqueue is full when every box of the array is full.is full.

• The easiest way to detect this is to store the The easiest way to detect this is to store the bqueue's current size (qcount) and maximum bqueue's current size (qcount) and maximum capacity (qcapacity), and test if they are equal.capacity (qcapacity), and test if they are equal.

• qcount will increase when an element is added, qcount will increase when an element is added, decrease when one is removed.decrease when one is removed.

Page 34: 09. Queues

241-423 ADSA : Queues/9 34

BQueue Class full()

public boolean full(){ return (qcount == qcapacity);}

Page 35: 09. Queues

241-423 ADSA : Queues/9 35

BQueue Class push()public void push(T item){ // is queue full? if (qcount == qcapacity) throw new IndexOutOfBoundsException( "BQueue push(): queue full"); queueArray[qback] = item; // insert item qback = (qback+1) % qcapacity; // move qback forward

qcount++; // increment the queue size} // end of push()

Page 36: 09. Queues

241-423 ADSA : Queues/9 36

BQueue Class pop()public T pop(){ // is queue empty? if (count == 0) throw new NoSuchElementException( "BQueue pop(): empty queue");

// temporarily store the front item T item = queueArray[qfront];

// move qfront forward, so front element is 'deleted' qfront = (qfront+1) % qcapacity;

qcount--; // decrement the queue size return item; // return the old front item} // end of pop()

Page 37: 09. Queues

241-423 ADSA : Queues/9 37

5. Priority Queue Collection• In a priority queue, all the elements have priority

values.

• A deletion always removes the element with the highest priority.

Page 38: 09. Queues

241-423 ADSA : Queues/9 38

PQueue Interface

• The generic PQueue resembles a queue with the same method names.

interface PQueue<T> ds.util boolean isEmpty()

Returns true if the priority queue is empty and false otherwise.

T peek() Refer to value of the highest-priority item. If empty, throws a NoSuchElementException.

continued

Page 39: 09. Queues

241-423 ADSA : Queues/9 39

interface PQueue<T> ds.util T pop()

Removes the highest priority item from the queue and returns its value. If it is empty, throws a NoSuchElementException.

void push(T item) Inserts item into the priority queue.

int size() Returns the number of elements in this priority queue

Page 40: 09. Queues

241-423 ADSA : Queues/9 40

HeapPQueue Class

• The collection class HeapPQueue implements The collection class HeapPQueue implements the PQueue interface, using a Heap data the PQueue interface, using a Heap data structure which I'll explain in a later part.structure which I'll explain in a later part.

Page 41: 09. Queues

241-423 ADSA : Queues/9 41

HeapPQueue Class Example// create a priority queue of StringsHeapPQueue<String> pq = new HeapPQueue<String>();pq.push("green");pq.push("red");pq.push("blue");

// output the size, and element with highest prioritySystem.out.println(pq.size() + ", " + pq.peek());

// use pop() to empty the pqueue and list elements // in decreasing priority orderwhile ( !pq.isEmpty() ) System.out.print( pq.pop() + " ");

3, redred green blue

The priority for Stringsis alphabetical order