Title: Computer Science II
1Computer Science II
2Queues
- A queue is a linear collection whose elements are
added on one end and removed from the other - We say that queue elements are processed in a
first in, first out (FIFO) manner - Elements are removed from the queue in the same
order in which they are placed on the queue - A queue is consistent with the general concept of
a waiting line
3Queues
Adding an element
Removingan element
rear of queue
front of queue
4Queue Operations
5//
// Queue.java Java
Foundations // // Defines the interface to a
queue collection. //
package
javafoundations public interface QueueltTgt
// Adds the specified element to the rear of the
queue. public void enqueue (T element) //
Removes and returns the element at the front of
the queue. public T dequeue() // Returns
a reference to the element at the front of the
queue // without removing it. public T
first() // Returns true if the queue
contains no elements and false // otherwise.
public boolean isEmpty() // Returns the
number of elements in the queue. public int
size() // Returns a string representation
of the queue. public String toString()
6Radix Sort
- A radix sort is a unique that does not involve
comparisons - The technique used in the radix sort is based on
the structure of the sort key - Separate queues are created for each possible
value of each digit or character of the sort key - The number of queues, or the number of possible
values, is called the radix
7Radix Sort
- For example
- if we were sorting strings made up of lowercase
alphabetic characters, the radix would be 26, one
for each possible character - if we were sorting decimal numbers, then the
radix would be 10, one for each digit 0 to 9 - The radix sort makes a pass through the values
for each position in the sort key - if we are sorting decimal number of three digits
long, we will make three passes over the data
(once for the 1s position, once for the 10s
position, and finally for the 100s position)
8Radix Sort
- On the first pass, each number is put on the
queue corresponding to its 1s digit - On the second pass, each number is put on the
queue corresponding to its 10s digit - Finally, on the third pass, each number is put on
the queue corresponding to its 100s digit - Between passes, we retrieve the elements from the
queues in ascending queue order (0s queue, 1s
queue, etc.)
9Radix Sort (1st pass)
front of queue ?
442
503
312
145
250
341
325
102
420
143
Original list
10Radix Sort (2nd pass results)
front of queue ?
503
102
312
325
420
442
145
341
143
250
11Radix Sort (3rd pass results)
front of queue ?
145
102
143
250
312
341
325
442
420
503
12//
// RadixSort.java
Java Foundations // // Demonstrates the use of
queues in the execution of a radix
sort. //
import
javafoundations.ArrayQueue public class
RadixSort //---------------------------------
--------------------------------- // Perform
a radix sort on a set of numeric values.
//------------------------------------------------
------------------ public static void main
(String args) int list 7843,
4568, 8765, 6543, 7865, 4532, 9987, 3241,
6589, 6622, 1211 String
temp int digit, num
ArrayQueueltIntegergt digitQueues
(ArrayQueueltIntegergt)(new ArrayQueue10) (mor
e)
13 for (int digitVal 0 digitVal lt 9
digitVal) digitQueuesdigitVal new
ArrayQueueltIntegergt() // sort the list
for (int position0 position lt 3
position) for (int scan 0
scan lt list.length scan)
temp String.valueOf (listscan)
digit Character.digit (temp.charAt(3-position),
10) digitQueuesdigit.enqueue
(listscan) // gather
numbers back into list num 0
for (int digitVal 0 digitVal lt 9
digitVal) while
(!(digitQueuesdigitVal.isEmpty()))
listnum digitQueuesdigitVal
.dequeue().intValue() num
(more)
14 // output the sorted list for (int
scan 0 scan lt list.length scan)
System.out.println (listscan)
15Implementing Queues with Arrays
- When an element is removed from the queue it is
removed from index 0, and forces us to shift the
remaining elements one position toward the low
end - One array-based strategy for implementing a queue
is to fix one end (the front) of the queue at
index 0 of the array - The integer variable count represents the number
of elements currently in the queue, and the next
open cell in the array
16Implementing Queues with Arrays
- Our implementation adds a new element to the rear
of the queue, which is stored at the high end of
the array
A
B
C
D
E
Enqueue E
Dequeue A
Left-shift tocorrectqueue
17//
// LinkedQueue.java
Java Foundations // // Represents a linked
implementation of a queue. //
p
ackage javafoundations import
javafoundations.exceptions. public class
LinkedQueueltTgt implements QueueltTgt private
int count private LinearNodeltTgt front,
rear //--------------------------------------
--------------------------- // Creates an
empty queue. //--------------------------------
--------------------------------- public
LinkedQueue() count 0 front
rear null (more)
18 //---------------------------------------------
-------------------- // Adds the specified
element to the rear of this queue.
//------------------------------------------------
----------------- public void enqueue (T
element) LinearNodeltTgt node new
LinearNodeltTgt(element) if (count 0)
front node else
rear.setNext(node) rear node
count //------------------------------
----------------------------------- // The
following methods are left as Programming
Projects. //-----------------------------------
------------------------------ // public T
dequeue () throws EmptyCollectionException
// public T first () throws EmptyCollectionExcepti
on // public boolean isEmpty() //
public int size() // public String
toString()
19Implementing Queues with Circular Arrays
- The main problem with the array-based
implementations discussed previously is that
every time a dequeue operation is performed, the
remaining elements must be shifted - Turning around the queue so that the rear of the
queue is at index 0 does not solve the problem - The key is not to fix either end at a certain
position - Our solution we will use a circular array to
implement the queue
20Implementing Queues with Circular Arrays
- As elements are dequeued, the front of the queue
will move further into the array - As elements are enqueued, the rear of the queue
will also move further into the array - The challenge comes when the rear of the queue
reaches the end of the array - When this occurs, it wraps around to the front
of the array
21Implementing Queues with Circular Arrays
- The variable count is still needed to represent
the number of elements in the queue - However count no longer represents the location
for adding new elements - We use two new variables, front and rear, to
represent the location where the first element is
stored, and where the next available slot in the
array is located (respectively)
22Implementing Queues with Circular Arrays
A
B
front
3
4
C
6
rear
7
3
count
4
D
23Implementing Queues with Circular Arrays
- Using this strategy, once an element has been
added to the queue, it stays in one location in
the array until it is dequeued - No elements need to be shifted
- However, we must carefully manage the values of
front and rear
24The Changing State of a Circular Array Queue
A
B
C
D
E
A
B
C
D
E
A
B
C
D
E
front
rear
count
5
5
0
3
8
7
2
25//
// CircularArrayQueue.java
Java Foundations // // Represents an array
implementation of a queue in which neither //
end of the queue is fixed in the array. The
variables storing the // indexes of the front
and rear of the queue continually increment //
as elements are removed and added, cycling back
to 0 when they // reach the end of the
array. //
package
javafoundations import javafoundations.exception
s. public class CircularArrayQueueltTgt
implements QueueltTgt private final int
DEFAULT_CAPACITY 10 private int front,
rear, count private T queue (more)
26 //---------------------------------------------
-------------------- // Creates an empty
queue using the default capacity.
//------------------------------------------------
----------------- public CircularArrayQueue()
front rear count 0 queue
(T) (new ObjectDEFAULT_CAPACITY)
//------------------------------------------------
----------------- // Adds the specified
element to the rear of this queue, expanding
// the capacity of the queue array if
necessary. //----------------------------------
------------------------------- public void
enqueue (T element) if (count
queue.length) expandCapacity()
queuerear element rear (rear1)
queue.length count (more)
27 //---------------------------------------------
-------------------- // Creates a new array
to store the contents of this queue with //
twice the capacity of the old one.
//------------------------------------------------
----------------- public void
expandCapacity() T larger
(T)(new Objectqueue.length2) for
(int index0 index lt count index)
largerindex queue(frontindex)
queue.length front 0 rear
count queue larger
//------------------------------------------------
----------------- // The following methods
are left as Programming Projects.
//------------------------------------------------
----------------- // public T dequeue ()
throws EmptyCollectionException // public
T first () throws EmptyCollectionException
// public int size() // public boolean
isEmpty() // public String toString()
28Implementing Queues with Circular Arrays
- Note the interesting calculation used to compute
the new value of rear - When an enqueue operation fills in the last cell
of the array (at the largest index), the value of
rear must be set to 0, indicating that the next
element should be stored at index 0 - To update the value of rear, the calculation uses
the remainder operator () and the length of the
array
29Implementing Queues with Links
- Because a queue is a linear collection, we can
implement a queue as a linked list of LinearNode
objects, as we did with stacks - One important difference, however, is that we
will have to operate on both ends of the list - This will cause us to introduce an additional
reference variable (rear) that points to the last
element in the list
30Implementing Queues with Links
31//
// LinkedQueue.java
Java Foundations // // Represents a linked
implementation of a queue. //
p
ackage javafoundations import
javafoundations.exceptions. public class
LinkedQueueltTgt implements QueueltTgt private
int count private LinearNodeltTgt front,
rear //--------------------------------------
--------------------------- // Creates an
empty queue. //--------------------------------
--------------------------------- public
LinkedQueue() count 0 front
rear null (more)
32 //---------------------------------------------
-------------------- // Adds the specified
element to the rear of this queue.
//------------------------------------------------
----------------- public void enqueue (T
element) LinearNodeltTgt node new
LinearNodeltTgt(element) if (count 0)
front node else
rear.setNext(node) rear node
count //------------------------------
----------------------------------- // The
following methods are left as Programming
Projects. //-----------------------------------
------------------------------ // public T
dequeue () throws EmptyCollectionException
// public T first () throws EmptyCollectionExcepti
on // public boolean isEmpty() //
public int size() // public String
toString()
33Analysis of Stack and Queue Implementations
- Both stacks and queues can be implemented very
efficiently - In almost all cases, the operations are not
affected by the number of elements in the
collection - All operations for a stack (push, pop, peek,
etc.) are O(1)
34Analysis of Stack and Queue Implementations
- Almost all operations for a queue are O(1)
- The only exception is the dequeue operation for
the ArrayQueue implementation the shifting of
elements makes it O(n) - The dequeue operation for the CircularArrayQueue
is O(1) because of the ability to eliminate the
shifting of elements
35Ch. 15 Summary
- Ch 15 focused on
- discussing how stacks and queues work
conceptually - defining stack and queue abstract data types
- demonstrating how stacks and queues can be used
to solve problems - examining various stack and queue implementations
- analyzing and comparing stack and queue
implementations
36Review
- 1. A stack is a ___________________ data
structure. - a) LIFO
- b) FIFO
- c) link based
- d) array based
- e) none of the above
- Answer a
- Explanation A stack is a LIFO (last in, first
out) data structure. This means that the last
element to be put on the stack will be the first
element that is removed.
37- 2. Which of the following is not a valid postfix
expression? - a) 5 4
- b) 6 5 4 -
- c) 4 5
- d) 8 2 2 /
- e) all of the above are valid postfix
expressions - Answer c
- Explanation Choice c is in infix notation, not
postfix.
38- 3. Which of the following methods inserts an
element into a stack data structure? - a) enqueue
- b) dequeue
- c) push
- d) pop
- e) peek
- Answer c
- Explanation The push method inserts an element
into a stack.
39- 4. A queue is the ideal collection to use when
____________________ . - a) implementing a radix sort
- b) evaluating a postfix expression
- c) evaluating an infix expression
- d) implementing a quick sort
- e) none of the above
- Answer a
- Explanation A queue is ideal for implementing
a radix sort.
40- 5. It is only possible to implement a stack using
a linked structure. - Answer False
- Explanation A stack can be implemented using a
linked structure or an array-based structure.
41- 6. A queue is a FIFO structure.
- Answer True
- Explanation A queue is a FIFO structure,
meaning that the first element that is put in is
the first element that is inserted is the first
element that is removed. FIFO stands for
first-in-first-out.
42- 7. In a linked implementation of a stack, a
pushed element should be added to the end of the
list. - Answer False
- Explanation In a linked implementation of a
stack, a pushed element should be added to the
front of the list. If the element is added to
the end of the list, the pop operation would
require linear time, because we would need to go
through the entire element to get a pointer to
the next-to-last element in the list.
43- 8. In an array-based implementation of a stack,
which end of the contents of the array represents
the bottom of the stack and why? - Answer A stack is implemented as an array with
the bottom of the stack represented by index 0 of
the array. This is for efficiency if index 0
were the top, whenever an element is removed the
entire contents of the array would have to be
shifted down, which would require too much time.
44- 9. Suppose the following sequence of elements
are inserted into a stack and a queue in the
following order 50, 26, 32, 18, 26, 51. What is
the result of three pop operations of the stack
and three dequeue operations of the queue? - Answer Three pop operations of the stack will
result in 51, 26 and 18, in that order. Three
dequeue operations of the queue will result in
50, 26, and 32, in that order.
45- 10. Write a push method for a stack implemented
with an array. You may assume that the stack is
referenced by an array named stack, and that
there is an integer variable named count that
keeps track of the number of elements in the
stack. You may not assume that you have access
to an expandCapacity method (meaning that your
method should include code to expand the capacity
of the array if it is full). - Answer
- public void push(T element)
- if(count stack.length)
- T newStack new Tstack.length2
- for(int i 0 i lt stack.length i)
- newStacki stacki
- stack newStack
-
- stackcount element
-
46- 11. List the five basic operations on a stack.
- Answer The five basic operations on a stack are
push, pop, peek, isEmpty and size.