int fib(int n) { if (n < 1) { // error check return -1 } else if (n == 1) { // base case 1 return 1; } else if (n == 2) { // base case 2 return 1; } else { return fib(n-1) + fib(n-2); // recursive call } }
BinarySearch(A, start, end, element)
- if start ≥ end
- return false
- mid <- (high + low) /2
- if A[mid] = element
- return true
- else if A[mid] > element
- return BinarySearch(A, start, mid-1, element)
- else
- return BinarySearch(A, mid+1, end, element)
Look at the middle element, if this is it return success If the middle element is too large, search the bottom half of the list If the middle element is too small, search the top half of the list
By (Weak) Induction: Base: For a list of size 1, the midpoint will be that element we will find it, and thus return true or not find it and return false. Inductive Step: Assume the binary search works for an array of size k. Next Case: Prove for k+1 If we are searching a list of size k+1 we have three choices, Either it is the midpoint, in which case we will return true Or it is in one of the two lists, each of which are roughly of size k/2. We know, by the genenral case that the search will successfully work on any list smaller than k, so it will work on either of these two lists.
0 0 0 0 0 0 0 0 0 0 0 0 0 0 9 9 9 9 9 0 0 0 0 0 9 0 0 0 0 0 9 0 0 0 9 0 0 9 0 9 0 0 9 0 9 0 0 0 0 0 0 0 0 0 9 9 0 0 0 0 9 0 0 0 0 9 9 0 0 9 0 0 0 9 0 0 9 0 9 0 0 9 9 9 0 0 9 0 0 0 9 0 0 0 0 0 9 0 0 0 0 0 9 9 9 9 9 0 0 0
FloodFill(Picture, posx, posy, origColor, fillColor)
- if !Picture.valid(posx,posy)
- return
- if Picture.color(x,y) = origColor
- Picture.color(x,y) <- fillColor
- FloodFill(Picture, posx+1, posy, origColor, fillColor)
- FloodFill(Picture, posx-1, posy, origColor, fillColor)
- FloodFill(Picture, posx, posy+1, origColor, fillColor)
- FloodFill(Picture, posx, posy-1, origColor, fillColor)
ACK(m,n)A
- if m=0
- return n+1
- else if m >0 and n = 0
- return ACK(m-1,1)
- else
- return ACK(m-1, ACK(m, n-1))
Fib(n)MemFib(n)
- for i <- 1 to n do
- m[i] <- ∞
- return MemFib(n)
- if m[n] != ∞
- return m[n]
- if n = 1 or n = 2
- rv <- 1
- else
- rv <- MemFib(n-1) + MemFib(n-2)
- m[n] <- rv
- return rv