| 1 if n = 1,2 F(n) =| | F(n-1) + F(n-2) for n > 2
F(4) = F(3) + F(2) F(2) = 1 F(3) = F(2) + F(1) 1 + 1 = 2 F(4) = 2 + 1
F(6) = F(5) + F(4) F(4) = 3 from above F(5) = F(4) + F(3) 3 + 2 = 5 F(6) = 5 + 3 = 8
// assume only positive input int Fib(int n) { int returnValue; // handle the base case first; if (n == 1 or n == 2) { returnValue = 1; } else { returnValue = Fib(n-1) + Fib(n-2); } return returnValue; }
| 1 n = 0 Pow(x,n) = | x n = 1 | x* Pow(x,n-1) n > 1 Pow(x,n) = |
float Pow(float x, int n) { // base case number 1 if (n == 0) { return 1; // base case number 2 } else if (n == 1) { return x; // recursive case } else { return x * Pow(x, n-1); } }
| 0 n = 0 factorial(n) = | | n*factorial(n-1) n> 0
long Factorial(int n) { if (n == 0) { return 1; } return n*Factorial(n-1); }
void PrintString(string s) { if (s.size() != 0) { cout <<s[0]; PrintString(s.substr(1,string::npos)); } return; }
find the middle element (start+stop)/2 if the middle element matches the key return true, middle position, .... else if the key is less than the middle element return the results of a search of the lower half of the array else return the results of a search of the upper half of the array
int BinarySearch(string s, int start, int stop, char key) { int mid; if (start > stop) { // we need some indication of not found return -1; } else { mid = (start + stop) /2; if (s[mid] == key) { return mid; } else if (key < s[mid]){ return BinarySearch(s,start, mid-1, key); } else { return BinarySearch(s,mid+1,stop, key); } } }