Hello World! An Invitation to Computer Science

Lecture slides on algorithms applied to lists

Thursday, January 31, 2008




Key ideas from last time




Division via repeated subtraction

  input dividend, divisor
  quotient ← 0
  remainderdividend
  while remainder &ge divisor:
    remainderremainder - divisor
    quotientquotient + 1
  output quotient, remainder



Algorithms that operate on lists




Adding numbers on a list

  input n; L1, L2, ... Ln
  sum ← 0
  i ← 1
  while in:
    sumsum + Li
    ii + 1
  output sum



Sequential search

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

Observe: Boolean variables and conjunction




Finding largest item on a list

  input n; L1, L2,  ... Ln
  maxL1
  i ← 2
  while in:
    if Li > max:
      maxLi
    ii + 1
  output max

Why do we assume n > 0 and start i at 2?




Where analogies break down




Pattern matching