Download presentation
Presentation is loading. Please wait.
2
Binary Search Example CSC 172 SPRING 2004 LECTURE 5
3
Reminder Project Due Friday 5PM
4
Lookup: Array public boolean lookup(Object o){ for (int j = 0 ; j < length;j++) if (datum[j].equals(o)) return true; return false; }
5
So, suppose we kept the list sorted Each insert now costs “n” But what happens to lookup?
6
Guessing Game I’m thinking of a number 1<=x<=64 I’ll tell you “higher” or “lower” How many guesses do you need? 29 47 33 You know with “higher” or “lower” you can divide The remaining search space in half (i.e. log 2 (64)==6)
7
Binary Search Recursively divide the array half until you find the item (if it is sorted).
8
Lookup on sorted array public boolean lookup(Object o) { return lookupRange(Object o,0,length-1); }
9
LookupRange: Binary Search public static void lookupRange(Object o, int lower,int higher){ if (lower > higher) return false; else { int mid = (low + high)/2; if (datum[mid].compareTo(o) < 0) return lookupRange(o,lower,mid); else if (dataum[mid].compareTo(o) > 0) return lookupRange(o,mid+1,higher); else return true; // o == datum[mid] }
10
All very well and good But can it help me be politically aware? YES! In order to be aware of a candidate’s position we have to call them and talk. So, you have to look up someone’s phone number in the phone book. You can save time by using binary search.
11
VOTE FOR PRESIDENT John Kerry Howard Dean Wesley Clark John Edwards Joe Lieberman George Bush (Write in)
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.