EXAMINATIONS 2006 SUMMER TRIMESTER. COMP103 Introduction to Data Structures and Algorithms

Similar documents
COMP 103 Introduction to Data Structures and Algorithms

EXAMINATIONS 2005 END-YEAR. COMP 103 Introduction to Data Structures and Algorithms

EXAMINATIONS 2011 Trimester 2, MID-TERM TEST. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS

EXAMINATIONS 2012 Trimester 1, MID-TERM TEST. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS

EXAMINATIONS 2012 MID YEAR. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS

EXAMINATIONS 2015 COMP103 INTRODUCTION TO DATA STRUCTURES AND ALGORITHMS

SOLUTIONS. COMP103 Introduction to Data Structures and Algorithms

CONTAINS SOLUTIONS!!!

WITH SOLUTIONS!!! WARNING: THIS COPY CONTAINS SOLUTIONS!!! COMP103 Introduction to Data Structures and Algorithms

EXAMINATIONS 2016 TRIMESTER 2

COMP 103. Data Structures and Algorithms

EXAMINATIONS 2010 END YEAR. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS

EXAMINATIONS 2017 TRIMESTER 2

COMP103 Test. 5 Sept, 2007

EXAMINATIONS 2010 MID YEAR. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS

Te Whare Wananga o te Upoko o te Ika a Maui EXAMINATIONS 2003 END-YEAR COMP 103. Data Structures and Algorithms

EXAMINATIONS 2011 END YEAR. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS

****** NOTE!! THIS CONTAINS SOLUTIONS ***** TRIMESTER 2

Model Solutions. COMP 103: Mid-term Test. 21st of August, 2014

Model Solutions. COMP 103: Test May, 2013

U N I V E R S I T Y O F W E L L I N G T O N EXAMINATIONS 2018 TRIMESTER 2 COMP 103 PRACTICE EXAM

Model Solutions. COMP 103: Test April, 2013

Family Name:... Other Names:... ID Number:... Signature... Model Solutions. COMP 103: Test 1. 9th August, 2013

U N I V E R S I T Y O F W E L L I N G T O N EXAMINATIONS 2018 TRIMESTER 2 COMP 103 INTRODUCTION TO DATA STRUCTURES AND ALGORITHMS

COSC 2007 Data Structures II Final Exam. Part 1: multiple choice (1 mark each, total 30 marks, circle the correct answer)

EXAMINATIONS 2013 COMP 103 INTRODUCTION TO DATA STRUCTURES AND ALGORITHMS

Model Solutions. COMP 103: Mid-term Test. 19th of August, 2016

U N I V E R S I T Y O F W E L L I N G T O N EXAMINATIONS 2018 TRIMESTER 2 COMP 103 INTRODUCTION TO DATA STRUCTURES AND ALGORITHMS

COMP 103 : Test. 2018, Sept 12//(Corrected)

COMP 103 : Test. 2018, Sept 12//(Corrected) ** WITH SOLUTIONS

CPSC 211, Sections : Data Structures and Implementations, Honors Final Exam May 4, 2001

CSE373 Fall 2013, Final Examination December 10, 2013 Please do not turn the page until the bell rings.

COMP 103 : Test. 2019, Jan 9 ** WITH SOLUTIONS **

COS 226 Midterm Exam, Spring 2009

COMP 250 Midterm #2 March 11 th 2013

Summer Final Exam Review Session August 5, 2009

CSCE 2014 Final Exam Spring Version A

CSE 332 Autumn 2013: Midterm Exam (closed book, closed notes, no calculators)

Faculty of Science FINAL EXAMINATION COMP-250 A Introduction to Computer Science School of Computer Science, McGill University

(f) Given what we know about linked lists and arrays, when would we choose to use one data structure over the other?

CS171 Midterm Exam. October 29, Name:

CS 151 Name Final Exam December 17, 2014

1) What is the primary purpose of template functions? 2) Suppose bag is a template class, what is the syntax for declaring a bag b of integers?

CS 314 Final Fall 2011

University of Waterloo Department of Electrical and Computer Engineering ECE 250 Algorithms and Data Structures

A6-R3: DATA STRUCTURE THROUGH C LANGUAGE

CSE373 Fall 2013, Midterm Examination October 18, 2013

Computer Science Foundation Exam

CSE373 Fall 2013, Final Examination December 10, 2013 Please do not turn the page until the bell rings.

FINAL EXAMINATION. COMP-250: Introduction to Computer Science - Fall 2011

Recitation 9. Prelim Review

1. [1 pt] What is the solution to the recurrence T(n) = 2T(n-1) + 1, T(1) = 1

COMP 103. Mid Trimester Test 17 August 2006

CSE 332 Spring 2014: Midterm Exam (closed book, closed notes, no calculators)

182 review 1. Course Goals

UNIVERSITY OF WATERLOO DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING E&CE 250 ALGORITHMS AND DATA STRUCTURES

FINAL EXAMINATION. COMP-250: Introduction to Computer Science - Fall 2011

University of Waterloo Department of Electrical and Computer Engineering ECE250 Algorithms and Data Structures Fall 2014

CS61BL Summer 2013 Midterm 2

CS 307 Final Spring 2011

CS 314 Final Fall 2012

CS210 (161) with Dr. Basit Qureshi Final Exam Weight 40%

Total Score /15 /20 /30 /10 /5 /20 Grader

INSTITUTE OF AERONAUTICAL ENGINEERING

Total Score /1 /20 /41 /15 /23 Grader

HEAPS & PRIORITY QUEUES

CSL 201 Data Structures Mid-Semester Exam minutes

CS 151 Name Final Exam December 17, 2014

CSE 373 Spring 2010: Midterm #1 (closed book, closed notes, NO calculators allowed)

Prelim 2 SOLUTION. 5:30 PM, 25 April Total Question Name Short Search/ Collections Trees Graphs

CSE 332 Spring 2013: Midterm Exam (closed book, closed notes, no calculators)

Computer Science E-22 Practice Final Exam

Topic 10: The Java Collections Framework (and Iterators)

CSE 373 Winter 2009: Midterm #1 (closed book, closed notes, NO calculators allowed)

MULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR

Prelim 2. CS 2110, November 20, 2014, 7:30 PM Extra Total Question True/False Short Answer

Abstract vs concrete data structures HEAPS AND PRIORITY QUEUES. Abstract vs concrete data structures. Concrete Data Types. Concrete data structures

Points off Total off Net Score. CS 314 Final Exam Spring Your Name Your UTEID

CSE 373 Autumn 2010: Midterm #1 (closed book, closed notes, NO calculators allowed)

Course Review. Cpt S 223 Fall 2009

CS134 Spring 2005 Final Exam Mon. June. 20, 2005 Signature: Question # Out Of Marks Marker Total

Course Review for Finals. Cpt S 223 Fall 2008

Section 05: Solutions

Draw the resulting binary search tree. Be sure to show intermediate steps for partial credit (in case your final tree is incorrect).

Final Examination CSE 100 UCSD (Practice)

Total Score /15 /20 /30 /10 /5 /20 Grader

Prelim 2. CS 2110, 16 November 2017, 7:30 PM Total Question Name Short Heaps Tree Collections Sorting Graph

COMP Data Structures

PRIORITY QUEUES AND HEAPS

Selection, Bubble, Insertion, Merge, Heap, Quick Bucket, Radix

UNIVERSITY OF WATERLOO DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING E&CE 250 ALGORITHMS AND DATA STRUCTURES

FINALTERM EXAMINATION Fall 2009 CS301- Data Structures Question No: 1 ( Marks: 1 ) - Please choose one The data of the problem is of 2GB and the hard

COS 226 Algorithms and Data Structures Fall Midterm

CSC 321: Data Structures. Fall 2016

CSC 321: Data Structures. Fall 2017

Computer Science 302 Spring 2007 Practice Final Examination: Part I

CMPSCI 187: Programming With Data Structures. Review for Final Exam David Mix Barrington 10 December 2012

ext Total Score /20 /20 /15 /20 /25 /5 Grader

COS 226 Midterm Exam, Spring 2011

York University AK/ITEC INTRODUCTION TO DATA STRUCTURES. Final Sample II. Examiner: S. Chen Duration: Three hours

Transcription:

T E W H A R E W Ā N A N G A O T E Ū P O K O O T E I K A A M Ā U I ÎÍÏ V I C T O R I A UNIVERSITY OF WELLINGTON EXAMINATIONS 2006 SUMMER TRIMESTER COMP103 Introduction to Data Structures and Algorithms Time Allowed: 3 Hours Instructions: 1. Attempt all of the questions. 2. Read each question carefully before attempting it. (Suggestion: You do not have to answer the questions in the order shown. Do the questions you find easiest first.) 3. This examination will be marked out of 180 marks, so allocate approximately 1 minute per mark. 4. Write your answers in the boxes in this test paper and hand in all sheets. 5. Non-electronic foreign language-english translation dictionaries are permitted. 6. Calculators are not permitted. 7. There is documentation on the relevant Java classes and interfaces at the end of the exam paper. Questions Marks 1. Basic Questions [18] 2. Sorting [20] 3. Analysis of Algorithms [15] 4. Programming with Collections [15] 5. Binary Search Trees [25] 6. General Trees [18] 7. Heaps [23] 8. Priority Queues [18] 9. Hashing [18] 10. Graphs [10] COMP103 continued...

Question 1. Basic Questions [18 marks] (a) [2 marks] Which collection type keeps items in order, but only allows you to add elements at one end and remove them from the other end? Queue (b) [2 marks] Suppose an array contains n items (in order). What is the worst case asymptotic ( Big O ) cost of the binary search algorithm? O( log(n)) (c) [2 marks] Name a sorting algorithm with a worst case asymptotic ( Big O ) cost of O(n log(n)). Merge Sort or Heap Sort Consider the diagram below of a variable containing a linked list. Assume that each node of the list has the fields item and next. (d) [2 marks] What is the worst case asymptotic ( Big O ) cost of removing the last item from the above linked list? O( n) (e) [2 marks] What is the value of linkedlist.next.next.item in the above linked list? C (Question 1 continued on next page) COMP103 2 continued...

(Question 1 continued) (f) [2 marks] State the defining features of Set, Bag, and Map. (g) [2 marks] Can we have duplicates in a Binary Search Tree? No (h) [2 marks] If we are adding a value to a Hash Table using buckets, and the first bucket we look at already contains a value, where do we put the value? In the bucket (i) [2 marks] Draw a directed graph containing five nodes and five edges. COMP103 3 continued...

Question 2. Sorting [15 marks] The code on this page shows two sorting algorithms discussed in the lectures, Insertion Sort and Quick Sort. You may find it useful to refer to these functions as you answer the questions in this section. PrintArray is a method that prints out the contents of the array. The questions that follow will make reference to this print statement. The following is an implementation of Insertion Sort: 1 public void insertionsort(e[] data, int size, Comparator<E> comp){ 2 for (int i=1; i<size; i++) { 3 E item = data[i]; 4 int place = i; 5 while (place > 0 && comp.compare(item, data[place-1]) < 0) { 6 data[place] = data[place-1]; 7 place--; 8 9 data[place] = item; 10 System.out.print(i + ":: "); 11 PrintArray(data); // <------ The print statement 12 13 The following is an implementation of Recursive Quick Sort. There are many correct implementations of partition, two were discussed in the lectures: 1 public void quicksort(e[] data, int low, int high, Comparator<E> comp) { 2 if(high-low<2) 3 return; // base case 4 else { 5 int mid = partition(data, low, high, comp); 6 PrintArray(data); // <------ The print statement 7 quicksort(data,low,mid-1,comp); 8 quicksort(data,mid,high, comp); 9 10 (Question 2 continued on next page) COMP103 4 continued...

(Question 2 continued) (a) [8 marks] Suppose an array containing the following values is to be sorted using Insertion Sort. Show the state of the array printed by the first 5 calls to PrintArray. Refer to the code at the start of the sorting question to find out exactly when PrintArray is called. (Question 2 continued on next page) COMP103 5 continued...

(Question 2 continued) (b) [12 marks] Suppose an array containing the following values is to be sorted. Your co-worker has tried to sort the array by implementing recursive Quick Sort, but there are problems and the array was not sorted correctly. As the array does not change in the base case, your co-worker has given you an output of the contents of the array after each call to partition. Each step shows the values used for low, high, and pivot in that step. They would like you to help them debug their algorithm. For each step, if there are any errors in the array, circle the errors and write an explanation of why they indicate errors. You should ignore errors that resulted from earlier steps, when highlighting the errors in later steps. To make it easier, your co-worker has also labelled each item with a number indicating its correct position in the array. Note: the code shown at the start of the sorting question section is a correct implementation of recursive quick sort, it is not your co-workers incorrect implementation. COMP103 6 continued...

Question 3. Analysis of Algorithms [15 marks] For each of the following code fragments, assume that data is an array containing n int values (i.e., data.length is n). (a) [4 marks] How many lines of data values will be printed out and what is the asymptotic ( Big O ) cost expressed in terms of n? 1 for(int i = 0; i < data.length; i++) 2 for(int j = 0; j < data.length; j++) 3 System.out.println(data[j]); The outer loop runs n times, and the inner loop runs n times, to in total the print statement is run n n = n 2. Number of lines: n 2 Big O Cost: O( n 2 ) (b) [5 marks] How many lines of data values will be printed out and what is the asymptotic ( Big O ) cost expressed in terms of n? 1 for(int i = 0; i < data.length; i++) 2 for(int j = 0; j < i; j++) 3 System.out.println(data[j]); For the first time around the outer loop (i=0), the inner loop runs 0 times, on the second time around the outer loop (i=1), the inner loop runs 1 time, and each time the number of times the inner loop runs is 1 longer than the last. The outer loop runs n times, so the print statement is run 1 + 2 +... + n 1 times. Which by using the summation from the appendix is equal to n (n 1) 2. To calculate the Big O cost, this can be expanded to n2 2 n 2, but multiplying constants and lower order terms are dropped from Big O cost, which leaves the Big O cost as n 2. Number of lines: n (n 1) 2 Big O Cost: O( n 2 ) COMP103 7 continued...

(c) [6 marks] How many lines of data values will be printed out and what is the asymptotic ( Big O ) cost expressed in terms of n? 1 for(int i = 0; i < data.length; i++) 2 for(int j = i+1; j > i; j--) 3 for(int k = data.length; k > j; k--) 4 System.out.println(data[j]); The middle loop always runs exactly once and so can be ignored. The outer loop runs n times. The inner most loop runs in the same fashion as in the previous question, but in reverse order. First time it runs n-1 times, then n-2, then n-3, all the way down to 3, 2, 1 times. So the answer is exactly the same as in the previous question. Number of lines: n (n 1) 2 Big O Cost: O( n 2 ) COMP103 8 continued...

Question 4. Programming with Collections [15 marks] (a) [5 marks] printfile is a method that reads a file, one line at a time, and then writes it out to the screen. You are to complete the method printreversefile, which reads a file, one line at a time, and then prints it out in reverse order. Your code must use the Java Stack Collection to reverse the order of the items. 1 public void printfile(file file) { 2 try { 3 Scanner scanner = new Scanner(file); 4 while(scanner.hasnextline()) { 5 String line = scanner.nextline(); 6 System.out.println(line); 7 8 9 catch(filenotfoundexception e){ 10 public void printreversefile(file file) { Stack<String> stack = new Stack<String>(); try { Scanner scanner = new Scanner(file); while(scanner.hasnextline()) { String line = scanner.nextline(); stack.push(line); catch(filenotfoundexception e) { while(!stack.empty()) { System.out.println(stack.pop()); (b) [10 marks] A small company has one video camera and they would like to make a simple system for keeping track of reservations for use of the camera. There is at most one reservation of the camera for any one date. The reservation system needs to have three methods. You are to complete the code below to implement these three methods and to define the collection to hold the reservations. The first method is makereservation, which takes a date and name, and either makes the booking and prints out that the booking has been made or it says that the date has already been booked. The second method is checkreservation, which takes a date, and either prints out that there is no booking for that date, or prints out who has reserved the camera on that date. The third method is bookingsummary, which prints out a summary of who has bookings in the system. It should print out the names of all the people with bookings in the system, and along with each name should be the number of bookings that person has in the system. COMP103 9 continued...

public class ReservationSystem { private Map<Date, String> reservations = new HashMap<Date, String>(); public void makereservation(date date, String name) { if(reservations.containskey(date)) { System.out.println("Date already booked."); else { reservations.put(date, name); System.out.println("Your reservation has been made."); public void checkreservation(date date) { if(!reservations.containskey(date)) { System.out.println("No booking on that date."); else { System.out.println("Reserved for " + reservations.get(date)); public void bookingsummary() { Map<String, Integer> summary = new HashMap<String, Integer>(); for(string name: reservations.values()) { if(!summary.containskey(name)) summary.put(name, 0); int count = summary.get(name); System.out.println(count); summary.put(name, ++count); for(map.entry<string, Integer> count: summary.entryset()) { System.out.println(count.getKey() + ": " + count.getvalue()); COMP103 10 continued...

Question 5. Binary Search Trees [25 marks] (a) [3 marks] Draw a Binary Search Tree containing the letters G, A, Z, X, P, N, and E. The root should contain the letter N. (b) [2 marks] State the difference between Binary Tree and a Binary Search Tree? (c) [3 marks] Describe the difference between iterative and recursive algorithm? (d) [2 marks] Consider removal of a node from a Binary Search Tree when the node has two children. What will happen if during the removal we replace the node with two children with rightmost in the left sub tree instead of leftmost in the right sub tree? (Question 5 continued on next page) COMP103 11 continued...

(Question 5 continued) (e) [3 marks] What property must be true of a binary search tree (BST) for insertion/access/deletion to have O(log(n)) complexity in all cases? It must be balanced, (all leaves must be in the bottom two levels of the tree). (f) [4 marks] Consider the following diagram of a Set of numbers implemented as a Binary Search Tree. Show, on the diagram, what the tree would look like if the values 8, 26, 8, and 84 were added to the set. root: 19 4 57 3 7 28 85 13 25 38 58 92 9 15 27 32 41 97 (Question 5 continued on next page) COMP103 12 continued...

(Question 5 continued) (g) [8 marks] In the blank space below, draw what the following binary search tree would look like if the values 6, 28, 21, and 47 were removed, in that order. Either use the removal algorithm presented in class or state clearly the algorithm you are using. root: 21 4 47 3 13 28 73 7 25 38 59 92 6 10 27 32 41 97 COMP103 13 continued...

Question 6. General Trees [18 marks] (a) [4 marks] Write out the order in which nodes would be visited by a depth-first, right-to-left, in-order traversal of the following general tree. D Z C E T L S X R V K (b) [2 marks] Iterative depth-first traversal uses explicit stack. It is missing from a recursive traversal. Where is the stack when doing depth-first recursively? (Question 6 continued on next page) COMP103 14 continued...

(Question 6 continued) (c) [5 marks] Given a GeneralTree implementation (this is the same as GeneralTree used in assignment 7), complete the following method that returns the size of the tree. public class GeneralTree<KeyType> { private KeyType _rootvalue; private Set<GeneralTree<KeyType>> _children; public int size() { (d) [2 marks] Why does an in-order traversal of a ternary tree make no sense? (Question 6 continued on next page) COMP103 15 continued...

(Question 6 continued) (e) [5 marks] The following traversal method below does a depth first traversal of a binary tree using a stack. 1 public static void traversal(treenode start) { 2 Stack<TreeNode> tovisit = new Stack<TreeNode>(); 3 tovisit.push(start); 4 while (!tovisit.isempty()) { 5 TreeNode current = tovisit.pop(); 6 System.out.println(current.value); 7 if (current.getleft()!=null) 8 tovisit.push(current.getleft()); 9 if (current.getright()!= null) 10 tovisit.push(current.getright()); 11 12 Suppose traversal is called on the following tree: R S U T L M K J W C H N Z E D Draw the contents of the stack immediately after node N has been added to the stack. Stack: COMP103 16 continued...

Question 7. Heaps [23 marks] (a) [4 marks] Suppose a priority queue is implemented as a heap. Draw the heap after the following data items have been inserted. The letter is the value, and the number in brackets is the priority. Data Items: X (3), B (2), C (7), T (4) Hint: draw this heap as a tree rather than as an array. (b) [3 marks] Draw the new heap after the following data items have been inserted into the heap you created in question (e). Data Items: N (2), E (5), L (2), S (3) The HeapQueue class is an implementation of priority queues using a heap a complete, partially ordered binary tree in an array. (c) [2 marks] If a complete partially ordered binary tree is stored in an array, and the index of the root is 0, what are the indices of the children of the node at index i and the index of the parent of the node at index i? (2 * i + 1) and (2 * i + 2) (Question 7 continued on next page) COMP103 17 continued...

(Question 7 continued) (d) [1 mark] If a complete partially ordered binary tree is stored in an array, and the index of the root is 0, what is the index of the parent of the node at index i? (i - 1) / 2 (e) [6 marks] Complete the following pushup(int i ) method that moves the value at index i up the partially ordered tree into its correct position. Assume that the HeapQueue contains the following fields: private E[ ] data; private int count; private Comparator <E > comp; where comp is a comparator that considers values with higher priority to be larger than values with lower priority. private void pushup(int i){ if (i = = 0) return; int parent = (i 1)/2; if (comp.compare(data[parent], data[i]) < 0) E temp = data[i]; data[i] = data[parent]; data[parent] = temp; pushup(parent); COMP103 18 continued...

(Question 7 continued on next page) COMP103 19 continued...

(Question 7 continued) Suppose a heap contains the following items: H (2) B (4) E (6) T (7) U (4) X (11) R (8) D (8) (f) [4 marks] Draw the new heap after dequeue() has been called twice on the heap above. (g) [3 marks] Draw the heap after dequeue() has been called another two times on the heap resulting from the previous question. COMP103 20 continued...

Question 8. Priority Queues [18 marks] This question concerns a ManagePatients program that helps a hospital keep track of the patients it has to treat in the waiting room. The hospital processes patients in order of their priority, so the ManagePatients program uses a priority queue. The program has three actions: New Patient Asks the user for the details of a new patient, adds it to the priority queue, and prints out its details. Next Patient Removes the patient at the front of the priority queue and prints out the details of the patient, or a useful message if there are no more patients to treat. Report Queue Prints the number of patients in the priority queue, and all their details. The ManagePatients class on the facing page contains an incomplete method for each of these actions. The ManagePatients class uses the Patient class described below, and the standard Queue interface described in the appendix. public class Patient implements Comparable<Patient >{ private String category; private int timeofarrival;. / / One of critical, urgent, or non urgent / / time of arrival used to calculate waiting time / Constructor asks the user for the details of a new patient and fills in the field values / public Patient(String prompt){. / Returns a String with all the details of the patient / public String getdetails(){.. (Question 8 continued on next page) COMP103 21 continued...

(Question 8 continued) (a) [12 marks] Complete the three methods in the ManagePatients class below. COMP103 22 continued...

public class ManagePatients { / / Priority queue of all patients private Queue <Patient > patients= new HeapQueue<Patient >(); public ManagePatients(){. / Get new patient details from user, add it to the queue, print details to System.out / public void enqueuenewpatient(){ Patient p = new Patient("Enter details for new patient") patients.offer(p); System.out.println("Enqueued: "+p.getdetails()); / Take patient off front of queue and print its details. If queue is empty, print No Patients / public void NextPatientToProcess(){ Patient p = patients.poll(); if (p = = null) else System.out.printlntextArea.append("No patients"); System.out.printlntextArea.append(p.getDetails()); / Print how many patients are waiting, and all their details / public void reportqueue(){ System.out.println(patients.size() +" patients yet to process:"); for (Patient p : patients) System.out.println(p.getDetails()); (Question 8 continued on next page) COMP103 23 continued...

(Question 8 continued) There are three categories of patients: critical, urgent, and non urgent. All the critical patients are higher priority than the urgent packages, which are higher priority than the non urgent packages. Within each category, the patients that have waited the longest have the highest priority. (b) [6 marks] Two efficient implementations of a priority queue are: an array of Queues, indexed by the priority, one queue for each priority value, and a HeapQueue, using a partially ordered tree in an array. Given the above definition of priority, which implementation would be a good choice for the Manage Patients program? Explain why. First one. Because there are only three number of possible priorities otherwise it is a queue - order of arrival. COMP103 24 continued...

Question 9. Hashing [18 marks] (a) [3 marks] Typically we increase the capacity of a Hash Table with probing when it is only 70% full. Why don t we wait until the Hash Table is 100% full? Because the performance, especially for adding new items, becomes very slow when the Hash Table is nearly full, because there are so many collisions. (b) [2 marks] VUW Student ID s consist of 8 digits. Most recent ID s start with the digits 3000. Suggest a good hash function for VUW student ID s. (c) [5 marks] Draw the contents of the array after the following 10 values are inserted into a Hash Table that uses an overflow area to handle collisions. Note: do not increase the size of the array if the table becomes too full. value: B A J K E S L M Z Y hashed index: 1 6 3 0 6 5 1 6 4 1 Main Overflow 0 1 2 3 4 5 6 7 8 9 10 11 12 (Question 9 continued on next page) COMP103 25 continued...

(Question 9 continued) The OpenHashBag class implements the Bag interface using a hash table with probing. Part of its code is given below. public class OpenHashBag implements Bag { private Object[ ] data; private int count = 0; public OpenHashBag (int size) { data = new Object[size];. private int hash(object val){ if (val = = null) throw new NoSuchElementException(); return Math.abs(val.hashCode()) % data.length;. (d) [8 marks] Complete the following code for the containselement method, using linear probing. containselement returns true if an element of the Bag matches the argument. It returns false if there is no matching element in the bag. public boolean containselement (Object val) { COMP103 26 continued...

Question 10. Graphs [10 marks] (a) [6 marks] Draw an adjacency list representation of the following directed, unweighted graph. A B C F G D E (Question 10 continued on next page) COMP103 27 continued...

(Question 10 continued) (b) [2 marks] State one reason why a tree traversal algorithm might not work on a directed graph. Loops/cycles, sources (nodes that have no edges into them) (c) [2 marks] To turn a tree traversal algorithm into a graph traversal algorithm, one change you would usually make is to use an additional Set data structure. What would this Set contain at any given point during a graph traversal? The nodes that have already been visited during the traversal ******************************** COMP103 28

Appendices Possibly useful formulas: 1 + 2 + 3 + 4 + + k = k(k+1) 2 1 + 2 + 4 + 8 + + 2 k = 2 k+1 1 a + (a + b) + (a + 2b) + + (a + kb) = (2a+kb)(k+1) 2 a + as + as 2 + as 3 + + as k = ask+1 a s 1 Table of base 2 logarithms: n 1 2 4 8 16 32 64 128 256 512 1024 1,048,576 log(n) 0 1 2 3 4 5 6 7 8 9 10 20 Brief (and simplified) specifications of relevant interfaces and classes. public class Scanner { public boolean hasnext(); / / there is more to read public String next(); / / return the next token (word) public String nextline(); / / return the next line public int nextint(); / / return the next integer public interface Iterator<E> { public boolean hasnext(); public E next(); public void remove(); public interface Comparable <E>{ public int compareto(e o); public interface Comparator <E>{ public int compare(e o1, E o2); public class Math{ public static double random(); / / return a random number between 0.0 and 1.0 public interface Collection <E>{ public boolean isempty (); public int size (); public Iterator<E> iterator ();

public interface List <E>extends Collection <E>{ / / Implementations: ArrayList public E get (int index); public void set (int index, E element); public void add (E element); public void add (int index, E element); public void remove (int index); public void remove (Object element); public interface Set extends Collection <E> { / / Implementations: ArraySet, SortedArraySet, HashSet public boolean contains (E element); public void add (E element); public void remove (Object element); public interface Map <K, V> { / / Implementations: HashMap, TreeMap, ArrayMap public V get (K key); / / returns null if no such key public void put (K key, V value); public void remove (K key); public Collection<V> values (); public Set<Map.Entry<K, V> > entryset (); public interface Map.Entry <K, V> { public K getkey (); public V getvalue (); public interface Queue <E>extends Collection <E>{ / / Implementations: ArrayQueue, LinkedList public E peek (); / / returns null if queue is empty public E poll (); / / returns null if queue is empty public boolean offer (E element); public class Stack <E>implements Collection <E>{ public E peek (); public E pop (); public E push (E element); public boolean empty (); public class Arrays { public static <E> void sort(e[ ] ar, Comparator<E> comp); public class Collections { public static <E> void sort(list <E> list, Comparator<E> comp);

SPARE PAGE FOR EXTRA ANSWERS Cross out rough working that you do not want marked. Specify the question number for work that you do want marked.