Presentation is loading. Please wait.

Presentation is loading. Please wait.

RecursionRecursion Lecturer : Kritawan Siriboon, Room no. 913 Text : Data Structures & Algorithm Analysis in C, C++,… Mark Allen Weiss, Addison Wesley.

Similar presentations


Presentation on theme: "RecursionRecursion Lecturer : Kritawan Siriboon, Room no. 913 Text : Data Structures & Algorithm Analysis in C, C++,… Mark Allen Weiss, Addison Wesley."— Presentation transcript:

1 RecursionRecursion Lecturer : Kritawan Siriboon, Room no. 913 Text : Data Structures & Algorithm Analysis in C, C++,… Mark Allen Weiss, Addison Wesley

2 0! = 1 1! = 1 2! = 2 * 1 3! = 3 * 2 * 1 4! = 4 * 3 * 2 * 1 5! = 5 * 4 * 3 * 2 * 1 Factorial n! = 1 if n=0, n=1 n! = n*(n-1)*(n-2) *...*1 if n>1 int fac (int n) //n>=0 { int prod = 1; for (int i=n; i>=1; i--) int prod *= i; return prod; }

3 int facR (int n) { //n>=0 if (n<=1) return 1; else return n * facR(n-1); } 0! = 1 1! = 1 * 0! 2! = 2 * 1! 3! = 3 * 2! 4! = 4 * 3! n! = 1 if n=0, n=1 n! = n * (n-1)! if n>0 Recursion VS Iteration recursive ใน term ของ มันเอง //base(simple) case //recursion 0! = 1 1! = 1 * 1 2! = 2 * 1 3! = 3 * 2 * 1 4! = 4 * 3 * 2 * 1 Rule : recursion must have base case. infinite? !!!

4 Definition : Recursion Iterative (Iterate = repeat) Recursive : in term of itself Recursive Definition : Define in term of itself Recursive function : Function that calls itself

5 Fibonaci Sequence 01123581321x.. x = ? f0f1f2f3... lohi new fib(n) = fib(n-1) + fib(n-2)if n>1 fib(n) = nif n=0, n=1 int fibR (int n) { // recursive, n>=0 if (n<=1) return n; else return fib(n-1) + fib(n-2); } fib n-2 fib n-1 fib n //simple case

6 Fibonaci Iteration int fib(int n) {// iterative, n>=0 int lo = 0;int hi = 1;int new; if (n<=1) return n; else { for( int i = 2; i<=n; i++){ new = hi + lo; lo = hi; hi = new; } return new; } } int fibR (int n) { n>=0 if (n<=1) return n; else return fib(n-1) + fib(n-2); } 0 1 1 2 3 5 8 13 21 x f 0 f 1 lo hi new lo hi new

7 search for x in a[low] to a[high] Binary Search 17.5 134517183133 if (low>high) //simple case return(-1); mid = (low+high)/2; if (x==a[mid]) //simple case return(mid); else if (x>a[mid]) search for x in a[mid+1] to a[high] else search for x in a[low] to a[mid-1] 0 123 4 5 6 7 low1 high1 L2 H2 L H H4L4 mid1 M2,M, Tail Recursion execute recursion as the last thing.

8 Stack of Recursion int fac (int n){//n>=0 int x, y; if (n<=1) return 1; else { x = n-1; y = fac(x); return n * y; } } 3 - n x yn x y 43- n x yn x y 32 - 43- n x yn x y 32- 1 - 43- n x yn x y 32- 21- 4 f4 fac(3) f3 fac(2) 2f2 fac(1) f1 1 y=fac(1) 43- n x yn x y 32- 21 y=fac(2) 43- n x yn x y 32 y=fac(3) 43 n x yn x y n x yn x y call: i = fac(4); Backtracking 24 2 6 2 1 1 6


Download ppt "RecursionRecursion Lecturer : Kritawan Siriboon, Room no. 913 Text : Data Structures & Algorithm Analysis in C, C++,… Mark Allen Weiss, Addison Wesley."

Similar presentations


Ads by Google