Download - CSC 205 Programming II Lecture 9 More on Recursion.

Transcript
Page 1: CSC 205 Programming II Lecture 9 More on Recursion.

CSC 205 Programming II

Lecture 9

More on Recursion

Page 2: 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?

Page 3: CSC 205 Programming II Lecture 9 More on Recursion.

Sample Code – writeBackward

Read sample code and execute Comparing results from different writeBackward methods

Discussions

Page 4: CSC 205 Programming II Lecture 9 More on Recursion.

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

Page 5: CSC 205 Programming II Lecture 9 More on Recursion.

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

Page 6: CSC 205 Programming II Lecture 9 More on Recursion.

Box Trace – Fibonacci Sequence

Page 7: CSC 205 Programming II Lecture 9 More on Recursion.

Binary Search – review

Page 8: CSC 205 Programming II Lecture 9 More on Recursion.

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;

}

}

Page 9: CSC 205 Programming II Lecture 9 More on Recursion.

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;

}

}

Page 10: CSC 205 Programming II Lecture 9 More on Recursion.

Homework

Read the sections on the Towers of Hanoi and Efficiency

Use the applet on www.mhhe.com/collins