CSC 205 Programming II
Lecture 9
More on Recursion
Recap: Recursion
How to recognize a recursive method?
What problems can be solved using a recursive solution?
How to trace recursive solutions?
Sample Code – writeBackward
Read sample code and execute Comparing results from different writeBackward methods
Discussions
An Exercise – palindromes
A palindrome is a string that is the same from right to left as from left to right
Examples EVE OTTO RADAR Madam, I’m Adam. (non-letter words ignored)
Iterative and recursive solutions Trace the recursive solution
The Fibonacci Sequence
Definition F(1) = F(2) = 1 F(n) = F(n-1) + F(n-2) n>2
The sequencen F(n)1 12 13 24 35 56 8
Box Trace – Fibonacci Sequence
Binary Search – review
Binary Search – an iterative solution
int binarySearch(String[] a, String key) {
int low = 0;
int high = a.length - 1;
while (low < high) {
int mid = (low + high) / 2;
if (a[mid].compareTo(key) < 0)
low = mid + 1;
else
high = mid;
}
return low;
}
}
Binary Search – a recursive solution
int binarySearch(int a, int low, int high, int key) {
int int = -1;
if (low<=high) {
int mid = (low + high) / 2;
if (a[mid] = key) index = mid;
else if (a[mid] > key)
index = binarySearch(a, low, mid-1, key);
else
index = binarySearch(a, mid+1, high, key);
}
return index;
}
}
Homework
Read the sections on the Towers of Hanoi and Efficiency
Use the applet on www.mhhe.com/collins
Top Related