Homework 7 - found = mid+1; else if...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
//p434 //#1 private boolean search( int first, int last, T searchOne) { boolean isFound; if (first > last) isFound = false ; else if (searchOne.equals(list[last])) isFound = true ; else isFound = search(first , last-1, searchOne); return found; } //#2-a. iterative search for a sorted array private boolean search( int first, int last, T SearchItem) { for ( int i=first ; i<=last ; i++){ if (searchItem.compareTo(list[i]) < 0) return false ; else if (searchItem.equals(list[i])) return true ; } return false ; } //#2-b. recursive search for a sorted array private boolean search( int first, int last, T searchItem) { if (first > last) return false ; if (searchItem.compareTo(list[first]) < 0) return false ; else if (searchItem.equals(list[first])) return true ; else found = search(first + 1, last, searchItem); return false ; } //#3. - for loop, comparisons until (8 == 8) - for loop, comparisons until (16 < 18)
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
//#5. private int binarySearch( int first, int last, T searchItem) { int mid = (first + last)/2; int found = -1; if (first > last) return found ; else if (searchItem.equals(list[mid]))
Background image of page 2
Background image of page 3
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: found = mid+1; else if (searchItem.compareTo(list[mid]) &lt; 0 ) found = binarySearch(first, mid - 1, searchItem); else found = binarySearch(mid + 1, last, searchItem); return found; } //#6. Implement the iterative binarySearch private static boolean binarySearch( int first, int last, T searchItem) { int mid = (first + last)/2; while ( mid &lt; last &amp;&amp; mid &gt;first) { if (searchItem.equals(list[mid])) return true ; else if (searchItem.compareTo(list[mid])&lt;0 ) { last = mid; mid = (first + mid)/2; } else { first = mid; mid = (mid + last)/2; } } return found; } //#7. private T searchLargest( int first, int last) { int mid = (first + last)/2; T largest = list[first] ; T a,b; if (first == last) return largest ; else { a = searchLargest(list, first, mid); b = searchLargest(list, mid+1, last); if (a.compareTo(b) &gt; 0) largest = a; else largest=b; } return largest; }...
View Full Document

This note was uploaded on 01/23/2012 for the course CS 111C taught by Professor Metzler during the Spring '11 term at City College of San Francisco.

Page1 / 3

Homework 7 - found = mid+1; else if...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online