



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




Data Stru tures
Midsemester Exam Version A
Name:
June 22, 2004
This exam has 4 questions. Ea h question starts on a new page. Please answer ea h question on its page. You may assume java.util has b een imp orted. There will b e no dedu tions for la k of ommenting. There will b e no dedu tions for la k of imp ort dire tives. There will b e no dedu tions for minor syntax errors.
publi stati boolean hasSum( int [ ℄ arr, int sum ) { for( int i = 0; i < arr.length; i++ ) { if( arr[ i ℄ == sum ) return true;
for( int j = i + 1; j < arr.length; j++ ) if( arr[ i ℄ + arr[ j ℄ == sum ) return true; }
return false; }
(a) What is the Big-Oh running time of hasSum? (b) If it takes 8 millise onds to return false for 1000 items, approximately how long would it take to return false for 2000 items? ( ) Using the Colle tions API, des rib e an algorithm (in English, no o de) that is more eÆ ient than the one ab ove, and provide the running time of your algorithm, with a brief justi ation. (d) Do es a hange to the problem that requires exa tly two items to sum (rather than allowing a single item) make the problem easier in a Big-Oh sense? Why/why not?
(a) Write a routine that given a student, returns the list of ourses the student is enrolled in. (b) Write a routine that given a ourse, returns the list of students registered for the ourse.
publi stati List getCourses( Map m, String student ) {
publi stati List getStudents( Map m, String ourse ) {
publi stati boolean hasSum( int [ ℄ arr, int sum ) { return hasSum( arr, 0, arr.length - 1, sum ); }
// Returns true if some subset of elements in arr[low..high℄ adds to sum // returns false otherwise // HINT: BASIC IDEA IS TO // return true if some a subset of elements in arr[low+1..high℄ adds to sum OR // some subset of elements in arr[low+1...high℄ adds to sum-arr[low℄ publi stati boolean hasSum( int [ ℄ arr, int low, int high, int sum ) {