Download presentation
Presentation is loading. Please wait.
Published byVincent Jennings Modified over 9 years ago
1
CSC 205 Programming II Lecture 9 More on Recursion
2
Recap: Recursion How to recognize a recursive method? What problems can be solved using a recursive solution? How to trace recursive solutions?
3
Sample Code – writeBackward Read sample code and execute Comparing results from different writeBackward methods Discussions
4
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
5
The Fibonacci Sequence Definition F(1) = F(2) = 1 F(n) = F(n-1) + F(n-2)n>2 The sequence nF(n)1 21 32 435 68
6
Box Trace – Fibonacci Sequence
7
Binary Search – review
8
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; }
9
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; }
10
Homework Read the sections on the Towers of Hanoi and Efficiency Use the applet on www.mhhe.com/collins www.mhhe.com/collins
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.