Binary Search Example - PowerPoint PPT Presentation

About This Presentation
Title:

Binary Search Example

Description:

So, suppose we kept the list sorted. Each insert now costs 'n' ... John Kerry. Howard Dean. Wesley Clark. John Edwards. Joe Lieberman. George Bush (Write in) ... – PowerPoint PPT presentation

Number of Views:154
Avg rating:3.0/5.0
Slides: 11
Provided by: thaddeusf
Category:

less

Transcript and Presenter's Notes

Title: Binary Search Example


1
Binary Search Example
  • CSC 172
  • SPRING 2004
  • LECTURE 5

2
Reminder
  • Project Due Friday 5PM

3
Lookup Array
  • public boolean lookup(Object o)
  • for (int j 0 j lt lengthj)
  • if (datumj.equals(o)) return true
  • return false

4
So, suppose we kept the list sorted
  • Each insert now costs n
  • But what happens to lookup?

5
Guessing Game
  • Im thinking of a number 1ltxlt64
  • Ill tell you higher or lower
  • How many guesses do you need?
  • 29
  • 47
  • 3
  • You know with higher or lower you can divide
  • The remaining search space in half (i.e.
    log2(64)6)

6
Binary Search
  • Recursively divide the array half until you find
    the item (if it is sorted).

7
Lookup on sorted array
  • public boolean lookup(Object o)
  • return lookupRange(Object o,0,length-1)

8
LookupRange Binary Search
  • public static void
  • lookupRange(Object o, int lower,int higher)
  • if (lower gt higher) return false
  • else
  • int mid (low high)/2
  • if (datummid.compareTo(o) lt 0)
  • return lookupRange(o,lower,mid)
  • else if (dataummid.compareTo(o) gt 0)
  • return lookupRange(o,mid1,higher)
  • else return true // o datummid

9
All very well and good
  • But can it help me be politically aware?
  • YES!
  • In order to be aware of a candidates position we
    have to call them and talk.
  • So, you have to look up someones phone number in
    the phone book.
  • You can save time by using binary search.

10
VOTE FOR PRESIDENT
  • John Kerry
  • Howard Dean
  • Wesley Clark
  • John Edwards
  • Joe Lieberman
  • George Bush
  • (Write in)
Write a Comment
User Comments (0)
About PowerShow.com