
CS112-2008S-15 Yet More Recursion: Min/Max 1
15-0: Recursion
•What is a really easy (small!) version of the problem, that I could solve immediately? (Base case)
•How can I make the problem smaller?
•Assuming that I could magically solve the smaller problem, how could I use that solution to solve the original
problem (Recursive Case)
15-1: Problems ...
•Some of the problems from this lecture are taken from
•javabat.com
•Really nice way to practice Java pr ogramming, check it out
15-2: Recursion
•sumDigits(n)
•Returns the sum of digits in n
•4321 =¿ 4 + 3 + 2 + 1 = 10
•5042 =¿ 5 + 0 + 4 + 2 = 11
•1776 =¿ 1 + 7 + 7 + 6 = 21
15-3: Recursion
int sumDigits(int n)
{
if (n == 0)
{
return 0;
}
else
{
return n % 10 + sumDigits(n / 10);
}
}
15-4: Recursion – Minimum
•Write a recursive function that returns the smallest value in the first size elements of an array of Comparable
objects
•Comparable minimum(Comparable A[], int size)
15-5: Recursion
Comparable minimum(Comparable A[], int size)
{
if (size == 0)
return null;
if (size == 1)
return A[0];
Comparable smallest = minimum(A, size - 1);
if (smallest.compareTo(A[size - 1]) < 0)
return smallest;
else
return A[size - 1];
}
15-6: Recursion – Minimum
•Write a tail-recursive function that returns the smallest value in the first nelements of an array of Comparable
objects