1.00/1.001 Lecture 10 Recursion Recursion • Recursion is a divide-and-conquer (or divideand-combine) approach to solving problems: method Recurse(Arguments) if (SmallEnough(Arguments)) // Termination return Answer else // “Divide” Identity= Combine( SomeFunc(Arguments), Recurse(SmallerArguments)) return Identity // “Combine” • If you can write a problem as the combination of smaller problems, you can implement it as a recursive algorithm in Java® Finding maximum of array Assume we can only find max of 2 numbers at a time. Suppose we want to find the max of a set of numbers, say 8 of them. 35 74 32 92 53 28 50 62 Our recursive max method calls itself: max(0,7) max(0,3) max(4,7) Greatest common divisor Given two non negative integers a < b, the greatest common divisor of a and b is: b if a == 0 Greatest common divisor of b%a and a Example gcd (12,18) = gcd (18%12, 12) = gcd (6,12) = gcd(12%6, 6) gcd(0, 6) = 6 import javax.swing.*; // To support simple input public class GCD { public static void main(String[] args) { String input= JOptionPane.showInputDialog("Enter a"); int a= Integer.parseInt(input); input= JOptionPane.showInputDialog("Enter b"); int b= Integer.parseInt(input); System.out.println("gcd is " + gcd(a,b)); } public static int gcd(int a, int b) { if(a == 0) return b; else return gcd(b%a,a); } } Call Sequence main( ) calls gcd(12, 18) gcd(12, 18 ) calls gcd(6, 12) returns 6 returns 6 gcd(6, 12 ) calls gcd(0, 6) 6 gcd( 0,6) returns 6 Summary • Recursive method calls itself, directly or indirectly (almost always directly in practice) • Recursion is based on divide and conquer: – Reduce an original problem to a sequence of smaller instances, until they are small enough to solve directly – Then, combine the subproblem solutions to construct the solution to the original problem • Recursion is one aspect of how a group of nonprocedural languages work – Java® is procedural: you tell computer what to do and how to do it (like C++, Visual Basic, …) – Nonprocedural languages: you tell computer what to do and it figures out how to do it (Prolog) Java® is a trademark or registered trademark of Sun Microsystems, Inc. in the United States and other countries.