Hello World! An Invitation to Computer Science

Lecture Slides: Algorithmic Efficiency

Monday, February 4, 2008 (and Thursday, February 7, 2008)


Key ideas from last time


Algorithms should be correct


Algorithms should be easy to understand

  input n
  sum ← 0
  i ← 1
  while in:
    sumsum + i
    ii + 1
  output sum

use common idioms where possible


Algorithms should be elegant

compactness counts...

  input n
  sum ← (n * (n + 1)) / 2
  output sum

... but may be at odds with ease of understanding


Algorithms should be efficient!


Analysis of algorithms


Order of magnitude


Sorting & Searching


Functional abstraction


Selection sort

  input n; L1, ..., Ln
  un
  while u > 0:
     p ← find position of max in L1, ..., Lu
     exchange Lp with Lu
     uu - 1

Exchange (a.k.a. Swap)

procedure: exchange places of two items on a list

  input n; L1, ..., Ln; x; y
  tLx
  LxLy
  Lyt

requires 3 computational steps
  independent of size of input list
  constant-time algorithm: O(1)

how much space does procedure take?


Finding maxima revisited

function: find position in list where max occurs

  input n; L1, L2,  ... Ln
  pos ← 1
  i ← 2
  while in:
    if Li > Lpos
      posi
    ii + 1
  output pos

requires 3+4(n-1) computational steps in worst case
  linear-time algorithm: O(n)


Analyzing selection sort