Presentation is loading. Please wait.

Presentation is loading. Please wait.

Fundamental in Computer Science Recursive algorithms 1.

Similar presentations


Presentation on theme: "Fundamental in Computer Science Recursive algorithms 1."— Presentation transcript:

1 Fundamental in Computer Science Recursive algorithms 1

2 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

3 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

4 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 = 1+2+3+…+N Now, prove by induction on recursive program 4

5 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

6 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

7 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

8 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

9 Discussion: Recursions and iterations Recursion replaces the loop Disadvantages of recursion Transform recursions to iterations Recursion elimination using stack 9

10 Interesting recursive applications Multiplication Division Raising a number to a power Modulo Merge sort 10

11 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

12 Backtracking algorithms Decision tree Games – Eight queens problem – Tic-tac-toe

13 อ้างอิง Robert Lafore, Data Structures & Algorithms in JAVA, SAMS, 2002. N.Wirth, Algorithms and Data Structures, 1985.


Download ppt "Fundamental in Computer Science Recursive algorithms 1."

Similar presentations


Ads by Google