Hello World! An Invitation to Computer Science

Lecture Slides: Binary Search

Monday, February 11, 2008


Key ideas from last time


Computational complexity


Searching for the information age


Review: sequential (linear) search

  input n; L1, ..., Ln; x
  found ← false
  i ← 1
  while not found and in
      if Li = x then
          found ← true
      else
          ii + 1
  output found

Works on any list - order not required.


Is linear search practical?

Depends on application in question.

Linear search is impractical for Web.


The importance of order


Binary Search

  input n; L1, ..., Ln; x
  found ← false
  low ← 1
  highn
  while not found and lowhigh
      mid ← (low + high) / 2  [round down]
      if Lmid = x then
          found ← true
      else
          if Lmid < x then
              lowmid + 1
          else
              highmid - 1
  output found

Analyzing binary search


Logarithms - yikes!


Siff's Law of Logarithms

Don't worry about the decimals!

The common logarithm of a number indicates
how many digits you need to write it down
.

precise formulation:  digits(x) = |log10(x)+1|

The binary logarithm of a number indicates
how much space is required to represent it on a computer
.


Siff's Law of Search

Number of particles in universe: ballpark 1075 ~ 2250
  if we use every electron in universe to represent data...
  ...binary search would still be fast!
  at least in theory... in practice, we'd never get there

no ordered list is too large to be searched

some unordered lists might be too large to put in order!