Lecture12MoreRecursion

# Lecture12MoreRecursion - What if you know the value at a...

This preview shows pages 1–14. Sign up to view the full content.

More Recursion

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
Reverse a string public String reverse (String str) { if (str.length() <= 1) return str; char first = str.charAt(0); String rest = str.substring(1); return reverse(rest) + first; }
Practice with simple math problems Sum integers to n Factorial Exponentiation Fibonacci sequence

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
Sum integers to n public static int sum (int n) { if (n < 1) return 0; // no work to do if (n == 1) return 1; //base case return n + sum (n-1); }
Factorial public static int factorial (int n) { // remember 0! is 1 }

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
Exponentiation public static int power (int base, int n) { if (base == 0) return 0; if (n <= 0) return 0; }
Fibonacci Sequence Fibonacci sequence: 1,1,2,3,5,8,13,21,?

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
Find nth number in the sequence using recursion public static int fibonacci (int nth) { }
Find minimum value in an array Simplest case? Reduction step

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: What if you know the value at a position and know the position of the minimum value in the rest of the array ? findMin ( ) private int [ ] array ; //assume it is filled public int findMin ( ) { int minLocation = findMinPosition(0); return array [ minLocation ]; } public int findMinLocation (int currentPos) { } public int findMinLocation (int currentPos) { if (currentPos == array.length – 1) return currentPos; } public int findMinLocation (int currentPos) { if (currentPos == array.length – 1) return currentPos; int smallestPosition = findMinLocation (currentPos+1); if ( array[currentPos] < array[smallestPosition]) { return currentPos; } else { return smallestPosition; } } Sort • How could you use the find minimum routine to sort an array?...
View Full Document

{[ snackBarMessage ]}

### Page1 / 14

Lecture12MoreRecursion - What if you know the value at a...

This preview shows document pages 1 - 14. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online