Fundamental in Computer Science Recursive algorithms 1
What’s it? A method calls itself Major characteristics – It calls itself. – Every call solves a smaller problem. – The base case exists, the point of return without calling itself. 2
Why? It provides a conceptual framework for solving problems. For some problem, it simplifies the code. It’s equivalent to mathematical induction It is used in – Divide and Conquer algorithms – Dynamic programming – Backtracking algorithms 3
Correctness proof Normally prove by induction – Prove the base case – Show if it’s true for the first few cases, then it can be extended to include the next case. – By induction, it’s true for all cases since “the next case” can be extended indefinitely. For example – To prove for any integer N ≥ 1, the sum of the first N integers, given by ∑ N i=1 i = …+N Now, prove by induction on recursive program 4
A Simple example Sum of the first N integers – long sumFirstNint(int n) { if (n==1) return 1; else return sumFirstNint(n-1)+n; } 5
Other examples Triangular numbers – The series of numbers 1,3,6,10,15,… – To find an n th number – Could be represented as triangles Factorials Binary search 6
Divide and Conquer Two recursive calls Divide – Smaller problems are solved recursively (except base cases) Conquer – The solution to the original problem is then formed from the solutions to the sub-problems Example – merge sort 7
Dynamic programming Solve sub-problems non-recursively by recording answers in a table. It is suitable in the problems where their sub- problems are not independent. Using divide and conquer will solve the same sub-problems many times. 8
Discussion: Recursions and iterations Recursion replaces the loop Disadvantages of recursion Transform recursions to iterations Recursion elimination using stack 9
Interesting recursive applications Multiplication Division Raising a number to a power Modulo Merge sort 10
Exercises in class Transform some recursions into iterations – gcd(long a, long b) – { if (b ==0) – Display a; else – gcd(b, a%b); – } modulo 11
Backtracking algorithms Decision tree Games – Eight queens problem – Tic-tac-toe
อ้างอิง Robert Lafore, Data Structures & Algorithms in JAVA, SAMS, N.Wirth, Algorithms and Data Structures, 1985.