Recursion and Problem Solving · CS101 Introduction to computing Recursion and Problem Solving A....

Post on 08-Mar-2020

15 views 0 download

transcript

CS101 Introduction to computing 

RecursionRecursionand

Problem Solving

A. Sahu and S. V .RaoDept of Comp. Sc. & Engg.Dept of Comp. Sc. & Engg.

Indian Institute of Technology Guwahati

Outline• Recursive Function (Continued…)

l–Example

• Problem Solving ExampleProblem Solving Example –Using modular functions–Using recursive functions–Using Arrays : Max Part SortUsing Arrays : Max, Part, Sort

A More Complex Recursive FunctionFibonacci Number SequenceA More Complex Recursive Function

if n = 1, then  Fib(n) = 1if n = 2, then  Fib(n) =  1if n > 2, then  Fib(n) =  Fib(n‐2) + Fib(n‐1)

Numbers in the series:Numbers in the series:1,  1,  2,  3,  5,  8,  13,  21,  34, ...

Fibonacci Sequence FunctionFibonacci Sequence Function

int Fib (int n){int Fib (int n){if (n == 1) ||(n == 2)) return 1;return 1;

elsereturn Fib(n-2)+Fib(n-1);return Fib(n 2)+Fib(n 1);

}

main(){int answer; answer=fib(5);

}printf(“5 th Fib Num is %d”, answer);}

Tracing with Multiple Recursive CallsTracing with Multiple Recursive Calls

Main :     answer = Fib(5)

Tracing with Multiple Recursive CallsTracing with Multiple Recursive Calls

Fib(5):     Fib returns Fib(3) + Fib(4)

Main :     answer = Fib(5)

Tracing with Multiple Recursive CallsTracing with Multiple Recursive Calls

Fib(3): Fib returns Fib(1) + Fib(2)

Fib(5):  Fib returns Fib(3) + Fib(4)

Fib(3):     Fib returns Fib(1) + Fib(2) 

Main :     answer = Fib(5)

Tracing with Multiple Recursive CallsTracing with Multiple Recursive Calls

Fib(3): Fib returns Fib(1) + Fib(2)

Fib(1):     Fib returns 1

Fib(5):  Fib returns Fib(3) + Fib(4)

Fib(3):     Fib returns Fib(1) + Fib(2)

Main :     answer = Fib(5)

Tracing with Multiple Recursive CallsTracing with Multiple Recursive Calls

Fib(3): Fib returns 1 + Fib(2)

Fib(5):  Fib returns Fib(3) + Fib(4)

Fib(3):     Fib returns 1 + Fib(2)

Main :     answer = Fib(5)

Tracing with Multiple Recursive CallsTracing with Multiple Recursive Calls

Fib(3): Fib returns 1 + Fib(2)

Fib(2):     Fib returns 1

Fib(5):  Fib returns Fib(3) + Fib(4)

Fib(3):     Fib returns 1 + Fib(2)

Main :     answer = Fib(5)

Tracing with Multiple Recursive CallsTracing with Multiple Recursive Calls

Fib(3): Fib returns 1 + 1

Fib(5):  Fib returns Fib(3) + Fib(4)

Fib(3):     Fib returns 1 + 1

Main :     answer = Fib(5)

Tracing with Multiple Recursive CallsTracing with Multiple Recursive Calls

Fib(5):  Fib returns 2 + Fib(4)

Main :     answer = Fib(5)

Tracing with Multiple Recursive CallsTracing with Multiple Recursive Calls

Fib(4): Fib returns Fib(2) + Fib(3)

Fib(5):  Fib returns 2 + Fib(4)

Fib(4):  Fib returns Fib(2) + Fib(3)

Main :     answer = Fib(5)

Tracing with Multiple Recursive CallsTracing with Multiple Recursive Calls

Fib(4): Fib returns Fib(2) + Fib(3)

Fib(2):     Fib returns 1

Fib(5):  Fib returns 2 + Fib(4)

Fib(4):  Fib returns Fib(2) + Fib(3)

Main :     answer = Fib(5)

Tracing with Multiple Recursive CallsTracing with Multiple Recursive Calls

Fib(4): Fib returns 1 + Fib(3)

Fib(5):  Fib returns 2 + Fib(4)

Fib(4):  Fib returns 1 + Fib(3)

Main :     answer = Fib(5)

Tracing with Multiple Recursive CallsTracing with Multiple Recursive Calls

Fib(4): Fib returns 1 + Fib(3)

Fib(3):     Fib returns Fib(1) + Fib(2)

Fib(5):  Fib returns 2 + Fib(4)

Fib(4):  Fib returns 1 + Fib(3)

Main :     answer = Fib(5)

Tracing with Multiple Recursive CallsTracing with Multiple Recursive Calls

Fib(1): Fib returns 1

Fib(4): Fib returns 1 + Fib(3)

Fib(3):     Fib returns Fib(1) + Fib(2)

Fib(1):     Fib returns 1

Fib(5):  Fib returns 2 + Fib(4)

Fib(4):  Fib returns 1 + Fib(3)

Main :     answer = Fib(5)

Tracing with Multiple Recursive CallsTracing with Multiple Recursive Calls

Fib(4): Fib returns 1 + Fib(3)

Fib(3):     Fib returns 1 + Fib(2)

Fib(5):  Fib returns 2 + Fib(4)

Fib(4):  Fib returns 1 + Fib(3)

Main :     answer = Fib(5)

Tracing with Multiple Recursive CallsTracing with Multiple Recursive Calls

Fib(2): Fib returns 1

Fib(4): Fib returns 1 + Fib(3)

Fib(3):     Fib returns 1 + Fib(2)

Fib(2):     Fib returns 1

Fib(5):  Fib returns 2 + Fib(4)

Fib(4):  Fib returns 1 + Fib(3)

Main :     answer = Fib(5)

Tracing with Multiple Recursive CallsTracing with Multiple Recursive Calls

Fib(4): Fib returns 1 + Fib(3)

Fib(3):     Fib returns 1 + 1

Fib(5):  Fib returns 2 + Fib(4)

Fib(4):  Fib returns 1 + Fib(3)

Main :     answer = Fib(5)

Tracing with Multiple Recursive CallsTracing with Multiple Recursive Calls

Fib(4): Fib returns 1 + 2

Fib(5):  Fib returns 2 + Fib(4)

Fib(4):  Fib returns 1 + 2

Main :     answer = Fib(5)

Tracing with Multiple Recursive CallsTracing with Multiple Recursive Calls

Fib(5):  Fib returns 2 + 3

Main :     answer = Fib(5)

Tracing with Multiple Recursive CallsTracing with Multiple Recursive Calls

Main :     answer = 5

Fib (N): Number of Recursive CallFib (N): Number of Recursive Call• Multiple Recursive CallsFib(N) Fib( 1) + Fib( 2)Fib(N) =Fib(n‐1) + Fib(n‐2)

Fib(20)Fib(20)

Fib(19) Fib(18)Fib(19) Fib(18)

Fib(17)Fib(18) Fib(17) Fib(17)

b( )Fib(16)

Fib (N): Number of Recursive CallFib (N): Number of Recursive Call• Multiple Recursive CallsFib(N) Fib( 1) + Fib( 2)Fib(N) =Fib(n‐1) + Fib(n‐2)

• Number of recursive call for N– Claim: Number of recursive call for Fib(n‐1) is higher than number of recursive call for Fib(n‐2)

– Denote number of recursive call for Fib(n)  = fn– fn‐1 > fn‐2

Fib (N): Number of Recursive CallFib (N): Number of Recursive Call• Can I Say : fn = fn‐1+fn‐2 > fn‐2+fn‐2 = 2. fn‐2• Then  fn >2.fn‐2 >2.2.fn‐4 >2.2.2.fn‐6

= =2n/2 f1 So f > 2n/2 … 2 f1 So  fn >  2• Number of recursive call require to 

b( ) /2compute Fib(n) is > 2n/2

• Can you calculate for 200 Fibonacci using y grecursive program – Will take at least 2100 recursive call : huge time and– Will take at least  2 recursive call  : huge time and space

Mutual RecursionRecursion doesn’t always occur because a routine calls itselfroutine calls itself...

Mutual Recursion occurs when twoMutual Recursion occurs when two routines call each other.

AA BB

B A

Mutual Recursion Example EvenOdd• Problem: Determine whether a number, N, is odd or even.,–If N is equal to 0, then n is even–N is odd if N‐1 is evenN is odd if N 1 is even

int Even(int N){ if(n==0) return 1;

int Odd(int N){ if(n==0) return 0;if(n==0) return 1;

return Odd(n-1);}

if(n==0) return 0;return Even(n-1);}

int main(){ printf(“E(20)=%d O(101)=%d”,

Even(20), Odd(101));}

Recursion Example: Problem Solvingint Reverse(int n) {int RevNum=0, Rem;RevNum=0;

int Reverse(int n) {static int Rev=0;

RevNum 0;while(n != 0) {Rem = n%10;RevNum=RevNum*10+Rem;

if(n ==0) return 0; Rev = Rev *10;

RevNum=RevNum 10+Rem;n=n/10;}

return RevNum; Rev = Rev + N%10;Reverse(N/10);return Rev;

return RevNum;}

return Rev; }

GCDGCD• By definition from Euclid’s algorithm y g• Recursive 

–GCD(a,b) if a > b  GCD(a%b, b) if b > a  GCD(a, b%a) 

• Code looks simpler

Recursive GCDRecursive GCD• Code looks simpler

( )int GCD(int a, int b) {if(a==0) return b;return gcd(b%a, a);

}

• Trace  35, 10 == > 10, 35  == > 5, 10 == > 0 , 5• Trace  10, 15 == > 5, 10 == > 0, 5• Trace  31, 2  == > 2, 31 ==> 1, 2 == >0, 1, , , ,

Modular C Code : Binary Searchint BinSrch(int Rmin,

int BinSrch(int Rmin,int Rmax, int X){

int Rmax, int X){while (Rmin<Rmax){

int mid; mid=(Rmin+Rmax)/2;if(X==mid)return mid;

mid=(Rmin+Rmax)/2;if(X==mid)

t id

( ) ;if (X>mid) returnBinSrch(mid+1 Rmax X);return mid;

if (X>mid) Rmin=mid+1;

BinSrch(mid+1,Rmax,X); else return BinSrch(Rmin,mid,X);

else Rmax=mid;}return -1;

}return -1;

}return 1;}

}

Binary Search AnalysisBinary Search Analysis• BinSrch(Range,X)

– mid=Range/2; – BinSrch(Range/2,X);( g / , );

• B(R) = B(R/2) + cB(R/4) + 2= B(R/4) + 2c

..= B(1) + log2R.c= c ceil(log R)= c.ceil(log2R)

P bl S l iProblem Solving Array, Function, Recursion y, ,

Problem Solving : ExamplesProblem Solving : Examples• Max of an Array

–Iterative and recursive procedure  • Sieve of Eratos‐thenes• Array Reversal• Array Reversal • Sorting an arraySorting an array

–Bubble sort 

Maximum of an ArrayMaximum  of an Array

Max of an Array• Iterative Approach• Iterative Approachint MaxOfAnArray(int A[], int n){i t i [0]int i, L=A[0];for(i=1; i<n; i++)

if(A[i]>L) L=A[i];

return L;}

• Number of steps required– N : linear code

Max of an Array: Recursive ApproachMax( 2 5 12 8 16 23 1 5)Max( 2, 5, 12, 8, 16, 23, 1, 5)= Max (Max of 1st Half, Max of 2nd Half) M (M (2 5 12 8) M (16 23 1 5) )= Max (Max(2,5,12,8),  Max(16,23,1,5) ) 

int RMax(int A[], int n1, int n2){int L1, L2; if(n1==n2) return A[n1];L1=Rmax(A, n1, (n1+n2)/2);L2=Rmax(A,(n1+n2)/2, n2);, ,if (L1>L2) return L1; else return L2;e se etu ;

}

Max of an Array: Recursive Approach• Number of steps required• Number of steps required

– R(N) =  R(N/2) + R(N/2) + C/=  2.R(N/2)+ C

=   4.R(N/4)+2C  = 8.R(N/8)+4C = N.R(1)+N/2.C= N +N/2.C = linear number of steps

int RMax(int A[] int n1 int n2){int RMax(int A[], int n1, int n2){int L1, L2; if(n1==n2) return A[n1];L1=Rmax(A, n1, (n1+n2)/2);L2=Rmax(A,(n1+n2)/2, n2);if (L1>L2) return L1; else return L2;}

Sieve of Eratosthenes

What is the sieve of Eratosthenes?What is the sieve of Eratosthenes?

• Used to find prime number between 2• Used to find prime number between 2 and N

• It works by gradually eliminating multiple of smallest unmark prime (x) in the given interval [2‐N]

Till x2 > N–Till  x2 > N• Let us see with an example

Sieve of Eratosthenes: 1 to 20• Current Prime 2 [2,3,4,5,6,7,8,9,10,11,12,13, 14,15,16,17,18,19,20] [ , , , , , , , , , , , , , , , , , , ]• Current Prime 2 [2,3,4,5, 6,7,8,9,10,11,12,13,14,15,16,17,18,19,20][2,3,4,5, 6,7,8,9,10,11,12,13,14,15,16,17,18,19,20] • Current Prime 3 List : [2 3 5 7 9 11 13 15 17 19]List :  [2, 3, 5, 7, 9, 11, 13, 15, 17, 19] • Current Prime 3 Li t [2 3 5 7 9 11 13 15 17 19]List :  [2, 3, 5, 7, 9, 11,13,15, 17,19] • Current Prime 5 and 5< ceil(sqrt(20))List :  [2, 3, 5, 7, 11, 13, 17,19]  //All are primes

Sieve of Eratosthenes#define STRIKED 0 //Happened to be composite#define STRIKED 0 //Happened to be composite#define NONSTRIKED 1 //Assumed Primevoid SeiveOfEratosthenes(int prime[MaxNum],

int N){int i,j, CP, SqrtM=sqrt(MaxNum)+1;for(i=0;i<MaxNum;i++) prime[i]= NONSTRIKED;for(i=2;i<SqrtM;i++){if ( i [i] STRIKED) tiif (prime[i]== STRIKED) continue ;CP=i; //current Primefor(j=2*CP;j<MaxNum; j=j+CP) //do strikingfor(j 2 CP;j<MaxNum; j j+CP) //do striking

prime[j]= STRIKED;}

}

Reversing an ArrayReversing an Array 

Reversing an ArrayReversing an Array • Approach

– Input:   10, 20, 33, 14,  5,  60, 70,  8 – Output:  8,  70, 60, 5,  14, 33, 20, 10– Mirror Image 10, 20, 33, 14,  5,  60, 70,  8 | 8, 70, 60,  5,  14, 33, 20, 10

• 10,  20,  33,  14,   5,   60,  70,   8

• 8,   70,  60,  5,   14,  33,  20,  10

Reversing an ArrayReversing an Array • 10,  20,  33,  14,   5,   60,  70,   8

• 8 70 60 5 14 33 20 10• 8, 70,  60,  5,   14,  33,  20,  10

• Start from both ends: Exchange element • Repeat for next elements form both sides till they meet each other

Reversing an Array : Iterative CodeReversing an Array : Iterative Code

void Reverse(int A[], int N,){int tmp,i=0,j=N-1; hil (i<j){while(i<j){

tmp=A[i]; [i]=A[j];A[j]=tmp;i=i+1i i+1, j=j-1;

}}

Reversing an Array : Recursive CodeReversing an Array : Recursive Code

void Reverse(int A[], int i, int j){

int tmp; if(i<j){

tmp=A[i]; A[i]=A[j];A[j]=tmp;Reverse(A i+1 j-1);Reverse(A, i+1, j-1);}

}}void ReverseArray(int A[], int N){

Reverse(A,0, N-1);}

Sorting an ArraySorting an Array 

Sorting an Array • Sorting  : Arrange  the element in some specific order

• Simpler case – non‐decreasing : smallest element at beginning and biggest element at endbiggest element at end  

– non‐increasing order: biggest element at beginning and smallest element at end  

l d• Example  Non‐sorted 30,  4,  7,  10,  12,  8,  2,  8S t d d i• Sorted : non‐decreasing 2,  4,  7,  8,  8,  10,  12,  30

Bubble SortBubble Sort1.Start at the beginning of the data set. 

2.Compare the first two elements, and if the first is greater than the second swaps themfirst is greater than the second, swaps them. 

3.Continue doing this for each pair of adjacent elements to the end of the data set.

4 Start again with the first two elements4.Start again with the first two elements, repeating until no swaps have occurred on the last passlast pass. 

Bubble Sort5 7 312 95

Bubble SortInvariant 

Last  PassNumberelements will be in 

sorted orderPass 1 5 7 312 95

5 7 312 95

sorted order 

Last 0 elements are in5 5 312 97

5 5 312 97

Last  0 elements are  in sorted order 

5 5 123 97

Bubble Sort5 5 97 123

Bubble SortInvariant 

Last  PassNumberelements will be in 

sorted orderPass 2 5 5 93 127

5 5 93 127

sorted order 

Last  1 element is in 

5 5 93 127

5 5 97 123

sorted orderShow in RED Box 

Bubble Sort5 5 93 127

Bubble SortInvariant 

Last  PassNumberelements will be in 

sorted order

Pass 3 5 5 97 123

5 5 97 123

sorted order 

Last  2 elements are in 

5 3 97 125sorted order

Show in RED Box 

Bubble Sort5 3 95 127

Bubble SortInvariant 

Last  PassNumberelements will be in 

sorted orderPass 4 5 3 97 125

3 5 97 125

sorted order 

Last  3 elements  are in sorted order

Show in RED Box 

Bubble Sort3 5 95 127

Bubble SortInvariant 

Last  PassNumberelements will be in 

sorted orderPass 5 3 5 97 125

3 5 97 125

sorted order 

Last  4 elements are in sorted order

Show in RED Box 

Sorted !!!

Bubble SortBubble SortInvariant 

Last  PassNumberelements will be in 

sorted orderAfter Pass 5

3 5 97 125sorted order 

All  5 elements are in sorted order

Show in RED Box 

Sorted !!!

Bubble Sort: C CodeBubble Sort:  C  Codevoid BubbleSort(int A[], int N){

int Pass j tmp;int Pass, j, tmp;for(Pass=0; Pass<N; Pass++){for(j=0; j<(N-Pass-1); j++){for(j 0; j<(N Pass 1); j++){

if(A[j] > A[j+1]){tmp=A[j]; A[j]=A[j+1];A[j+1]=tmp;

}}}

}//end Pass}//end Pass} //end BubbleSort

ThanksThanks