Exam 2012T2
Exam 2012T2
EXAMINATIONS — 2012
END-OF-YEAR
COMP 103
INTRODUCTION TO
DATA STRUCTURES
AND ALGORITHMS
Questions Marks
1. Collections and Sorting [15]
2. Using Priority Queues [18]
3. Using Maps [22]
4. Implementing a Collection [15]
5. Binary Search [15]
6. Trees [25]
7. Linked Lists [25]
8. Tree Traversals [13]
9. Hashing [18]
10. Debugging Tree Code [14]
(a) [3 marks] What is the difference between a priority queue and an ordinary queue?
An ordinary queue produces items strictly in order of arrival (first in, first out); a priority
queue produces items according to their priority, so that poll always returns the highest
priority item on the queue, regardless of when it was added to the queue.
(b) [3 marks] What are the differences between a Set and a List?
A set cannot have duplicates, and there is no order on the items; a list allows duplicates
and keeps items in some order such that you can access items by their position in the
order.
(c) [3 marks] If you need to sort a large collection of items, what is one reason why you might
choose NOT to use QuickSort.
QuickSort has a bad worst case cost (O(n2 )). or QuickSort is not stable. or There are more
efficient algorithms if the collection is almost sorted.
(d) [3 marks] HeapSort and MergeSort are both efficient sorting algorithms. Explain one advantage
of HeapSort over MergeSort.
HeapSort is an in-place sorting algorithm - it doesn’t require the additional space that
MergeSort needs
(e) [3 marks] You could use an ArrayList to store a set of items, rather than some implementation of
Set. Explain why it is generally better to use a Set class rather than ArrayList if you are storing a set
of items.
The Set classes impose constraints on the collection (such as no duplicates) that you would
have to implement yourself for an ArraySet. It is therefore easier and less error-prone to
use a Set class. Also, the Set classes can be much more efficient than an arraylist for
finding, adding, and removing items.
Suppose you are writing a program for the reception desk in a hospital emergency room. When
patients arrive, the nurse must collect details from the patient (name, etc) and assess the urgency for
treatment on a scale of 0 to 5. If the urgency is 5, the patient is sent straight through to the treatment
area. Other patients must wait, and their details are put on a priority queue. Whenever a doctor
becomes available, the nurse will remove the patient details from the front of queue, print them off,
and send the patient through to the treatment area.
Assume that one field of your EmergencyRoom program is the priority queue:
private PriorityQueue<Patient> waitingQueue = new PriorityQueue<Patient>();
(a) [8 marks] Complete the following acceptNewPatient and sendNextPatient methods that perform
the functions described above.
if (. . urgency
. . . . ==
. .5 . . . . . . . . . . . . . . . . . . . ){
patient . printDetails ();
UI. println ("Send patient through");
}
else {
. . waitingQueue.offer(patient
. . . . . . . . . . . . . );. . . . . . . . . . . . . . . .
}
}
if (. . waitingQueue.isEmpty()
. . . . . . . . . . . . . . . . . . . . . . . .
UI. println ("No patients waiting!!!");
}
else {
Patient patient = . . waitingQueue.poll()
. . . . . . . . . . . . . . . . . . . . . .
patient . printDetails ();
}
}
(Question 2 continued)
(b) [5 marks] For the priority queue to work correctly, Patient objects must be Comparable so that
higher priority patients (eg urgency: 4) are ordered before lower priority patients (eg urgency: 1).
Add whatever is required to the Patient class below to ensure that Patient objects are Comparable.
(You do not need to complete the askDetails and printDetails methods.)
class Patient {
private String name;
private int age;
private int urgency;
public int compareTo(Patient other){
public voidother.urgency
return setUrgency(int−u){ urgency = u; }
this.urgency;
public
// or void askDetails (){...}
public void
public printDetails (){...}other){
int compareTo(Patient
if (this.urgency > other.urgency) return −1;
if (this.urgency < other.urgency) return 1;
return 0;
}
(c) [5 marks] Describe how you would modify the EmergencyRoom class and the Patient class
(including your answer to part (b)) so that the priority queue not only ensured that higher urgency
patients are treated before lower urgency patients, but also that patients who arrived earlier are
treated before equal urgency patients who arrived later. Note: the PriorityQueue Class is part of the
Java Collections and cannot be modified.
Suppose you are writing a program for a web site that lets people vote for their favourite songs.
To vote, users enter the name of their song. Your program uses a Map (stored in the votes field) to
keep track of all the songs that have been entered and the number of votes for each song. The song
names (Strings) are the keys of the map, and the number of votes for the song are the values.
private Map<String, Integer> votes = new HashMap<String, Integer>();
(a) [7 marks] Complete the following addVote method that will record another vote in the votes
map. The parameter is the name of the song. Note that if this is the first vote for a song, the name
of the song will not yet be in the votes map, and must be added.
(b) [8 marks] Complete the following topSong method that will return the song with the highest
number of votes.
(c) [7 marks] Suppose your addVote method took 10 milliSeconds when votes had 1000 different
songs and you were adding a new vote for a song that was already in votes. Estimate the time
addVote would take to add a new vote for an existing song if votes contained 1,000,000 different
songs for each of the following cases. Justify your answer and show any working.
(i) Estimated time given that the votes field contains a hashMap.
10 milliseconds. Searching in a hash table (as long as it is not full), is O(1) and therefore
has approximately the same cost whatever the size of the table.
(ii) Estimated time if the votes field contained an arrayMap where the song–count pairs were stored
in an unordered array.
10 seconds (= 1000 × 10 milliseconds). It has to search through the array: the cost is O(n).
Since 1,000,000 songs is 1000 times 1000 songs, the cost of searching will be about 1000
times greater than 10 ms.
(iii) Estimated time if the votes field contained a sortedArrayMap where the song–count pairs were
stored in a sorted array, and the methods used binary search to find a song.
20 milliseconds. It has to do binary search on the array: the cost is O(log(n)). Searching
1000 songs required about 10 steps, searching 1,000,000 songs requires about 20 steps,
therefore the time will be roughly double. The cost may be a little less since there is some
fixed overhead.
This question concerns a YarraQueue class which implements a Queue collection using an array.
Part of the YarraQueue class is shown below. YarraQueue objects have a data field to hold the array
of values, a front field to hold the position of the value at the front of the queue, and a back field to
hold the position one before the value at the back of the queue. The diagram shows an example of
a queue with 5 values.
front: 11
back:
6
Values are added at the back of the queue and removed from the front of the queue. For example
if “A” and then “B” are added to the queue above and three items were removed, the queue would
now be:
front: 8
back:
4
When a queue is empty, both front and back will contain the value data.length-1. When a queue is
not empty, back will be less than front.
public class YarraQueue <E> extends AbstractQueue <E> {
public YarraQueue(){
data = (E[ ]) new Object[INITIALCAPACITY];
back = data.length−1; // Queue is initially empty
front = data.length−1;
}
public boolean isEmpty(){
return (back == data.length−1);
}
public boolean offer(E item){
if (item == null) throw new NullPointerException("null argument");
if (back<0) ensureCapacity();
data[back] = item;
back−−;
return true;
}
(a) [4 marks] Complete the following size method, which should return the number of items in the
queue. The cost of your size method should not depend on the number of items in the queue.
(b) [11 marks] Complete the following poll method, which should remove and return the value at
the front of the queue. If the queue is empty, it should return null. If it removes the last value in the
queue, front and back should be set to the appropriate value.
Consider the following find method that uses binary search to find the correct location for a value
in a sorted ArrayList of Strings. It contains a line of debugging code that will print out the values of
low and high at the end of each iteration of the loop.
(a) [6 marks] Suppose the ArrayList names contains the the following values:
”ant” ”bee” ”cat” ”dab” ”eel” ”fox” ”gnu” ”hen” ”jay” ”kea”
0 1 2 3 4 5 6 7 8 9
low high
Value returned: 4
(b) [5 marks] Complete the following containsValue method that returns true if a string is in the
given arrayList and false otherwise. It assumes the arrayList is sorted. Your answer should use the
find method on the facing page.
(c) [4 marks] Explain why the cost of the find method is always O(log(n)), if the ArrayList contains
n values.
In every case, find will halve the size of the region it is looking in (low..high) each time
round the loop. It is only possible to half size elements log(size) times.
(a) [6 marks] For each of the following trees, state whether it is a binary tree, a ternary tree, a general
tree, or not a tree, and give a brief justification of your answer.
D D F G
F H G E B R M R D C
K G A T U Y G E U X S H S X B
(A) binary because no nodes have more than two children. (Is also a ternary tree and a
general tree.)
(C) Ternary tree, because the non-leaf nodes have three children
(D) Not a tree, because some of the nodes have links to their siblings
Circle the correct option for each tree and give a brief justification of your answers. Assume that the
items are to be ordered alphabetically.
H A
D P D F
C J N T G Q L R
A G K Q V T U Y S
V
(A) (B)
(Question 6 continued)
(c) [5 marks] Show the state of the following heap after the highest ranked value (C) is removed
from the heap.
Hint: draw the tree.
C M S T U S Z ....
0 1 2 3 4 5 6
(d) [6 marks] Convert the following array of values into a heap. Use labeled arrows to show the
sequence of swaps that are required.
P T K V G M H ....
0 1 2 3 4 5 6
Suppose you are writing a LinkedQueue class that implements the Queue interface, using a linked
list to hold the values. Your implementation uses the following LinkedNode class.
(a) [5 marks] Draw a diagram of a LinkedQueue that contains the two values ”A” and ”B”. Show
the LinkedQueue object, its fields, and the LinkedNode objects.
(Question 7 continued)
(c) [3 marks] Complete the following isEmpty method for the LinkedQueue class:
(d) [8 marks] Complete the following poll method of the LinkedQueue class. Note, the cost of your
poll method should be O(1).
(Question 7 continued)
(e) [7 marks] Complete the following offer method of the LinkedQueue class. Note, the cost of your
offer method should be O(1).
} else {
back.setNext(new LinkedNode(value, null));
back = back.getNext();
}
return true;
}
Consider the following traversalDFS method that does a depth first traversal of a general tree, print-
ing out values in the nodes.
public void traversalDFS(GenTreeNode root){
if (root==null) return;
Stack<GenTreeNode> stack = new Stack<GenTreeNode>();
stack.push(root);
while (! stack.isEmpty()){
GenTreeNode node = stack.pop();
UI. print (node.getValue()+" ");
for(GenTreeNode child : node.getChildren()){
stack.push(child );
}
}
}
(a) [2 marks] Does traversalDFS do a pre-order or a post-order traversal of a tree? Justify your
answer.
(b) [4 marks] List the output of the traversalDFS method if it were called on the following tree.
Assume that the children of a node are shown in order from left to right.
C D G Z
E B F
AZGFDBCE
note that it puts all the children on to the stack in order so that the rightmost child is at
the top of the stack.
(Question 8 continued)
(c) [7 marks] Modify the traversal method above so that it does a breadth first traversal of a general
tree instead of a depth first traversal. It should print the above tree in the order A C D G Z E B F.
(a) [6 marks] The following table shows a mapping between characters and the hash values gen-
erated for those characters. Insert the characters into the array below, starting at the top row and
working your way down. Use linear probing to resolve collisions.
A ⇒ 4
B ⇒ 2
C ⇒ 4
D ⇒ 5
E ⇒ 3
F ⇒ 3
- - B E A C D F
0 1 2 3 4 5 6 7
(b) [6 marks] Consider the following (bad) hash function. Explain what makes it bad and what
effect it would have on a hash table.
The use of Math.random means that you will get a different hash value each time you call
it, so you will never be able to find an item again, after you have put it in the hash table.
(Question 9 continued)
(c) [6 marks]
The following remove method is for a HashSet that uses linear probing to resolve collisions, and
has a good hash method. Explain why this method might result in data (other than the item to be
removed) being lost.
You may assume that the data field points at a valid array.
private String [ ] data;
private int hash(String item) { ... }
Because it replaces the item it removes by null, it will lose any values that hashed to that
space or spaces on its left, but due to linear probing were placed in spaces to its right. A
later search for any such items will be stopped at the null, and prevent the search from
finding the items.
The following rotateRoot method is intended to “rotate” the root of a Binary Search Tree and its
right child without losing the BST ordering property. For example, it should change the tree on the
left into the tree on the right. The current root is moved to the left, its right child becomes the root,
and one of its grandchildren is also moved to the left.
However, rotateRoot has errors.
root: root:
E K
rotateRoot()
B K E N
A C G N B G M P
F M P A C F
private BSTNode root; // contains the root node of a Binary Seach Tree
:
public void rotateRoot(){
root = root . right ;
root . left = root ;
root . right . left = root . left . right ;
}
(a) [6 marks] Draw the tree that will actually result if rotateRoot is called on the tree on the left
above.
root:
B K
A C G N
F M P
(Question 10 continued)
root = oldRoot.right ;
root . left = oldRoot;
root . left . right = oldRightLeft ;
} .
********************************
COMP 103 29
SPARE PAGE FOR EXTRA ANSWERS
class Collections
public static void sort( List <E>)
public static void sort( List <E>, Comparator<E>)
public static void shuffle ( List <E>, Comparator<E>)
class Arrays
public static <E> void sort(E[ ] ar, Comparator<E> comp);
class Random
public int nextInt ( int n); // return a random integer between 0 and n−1
public double nextDouble(); // return a random double between 0.0 and 1.0