Anda di halaman 1dari 204

Recursion in C

Fundamentals of Computing (ESc 101A)


Lecture Notes 10

Raghunath Tewari
rtewari@cse.iitk.ac.in

Indian Institute of Technology, Kanpur

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

What is Recursion?

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

What is Recursion?

Recursive Function in C
A function defined in terms of itself is called a recursive function.
The process is known as recursion.

Some examples:

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

What is Recursion?

Recursive Function in C
A function defined in terms of itself is called a recursive function.
The process is known as recursion.

Some examples:
- Factorial: n! = n (n 1)!

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

What is Recursion?

Recursive Function in C
A function defined in terms of itself is called a recursive function.
The process is known as recursion.

Some examples:
- Factorial: n! = n (n 1)!
- Fibonacci numbers: F (n) = F (n 1) + F (n 2)

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

What is Recursion?

Recursive Function in C
A function defined in terms of itself is called a recursive function.
The process is known as recursion.

Some examples:
- Factorial: n! = n (n 1)!
- Fibonacci numbers: F (n) = F (n 1) + F (n 2)
The argument must change in between calls.

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

What is Recursion?

Recursive Function in C
A function defined in terms of itself is called a recursive function.
The process is known as recursion.

Some examples:
- Factorial: n! = n (n 1)!
- Fibonacci numbers: F (n) = F (n 1) + F (n 2)
The argument must change in between calls.
There must be one or more base case (also known as stopping
condition).

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

What is Recursion?

Recursive Function in C
A function defined in terms of itself is called a recursive function.
The process is known as recursion.

Some examples:
- Factorial: n! = n (n 1)!
- Fibonacci numbers: F (n) = F (n 1) + F (n 2)
The argument must change in between calls.
There must be one or more base case (also known as stopping
condition).
- Factorial: 1! = 1.

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

What is Recursion?

Recursive Function in C
A function defined in terms of itself is called a recursive function.
The process is known as recursion.

Some examples:
- Factorial: n! = n (n 1)!
- Fibonacci numbers: F (n) = F (n 1) + F (n 2)
The argument must change in between calls.
There must be one or more base case (also known as stopping
condition).
- Factorial: 1! = 1.
- Fibonacci numbers: F (1) = 1 and F (2) = 1.

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

What is Recursion?

Recursive Function in C
A function defined in terms of itself is called a recursive function.
The process is known as recursion.

Some examples:
- Factorial: n! = n (n 1)!
- Fibonacci numbers: F (n) = F (n 1) + F (n 2)
The argument must change in between calls.
There must be one or more base case (also known as stopping
condition).
- Factorial: 1! = 1.
- Fibonacci numbers: F (1) = 1 and F (2) = 1.
Argument values move towards the base case.

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Recursion in C
Example of a Recursive Function Factorial Function

1 #include<stdio.h>
2
3 int fact(int n){
4 if (n==0) return 1;
5 else return n*fact(n-1);
6 }
7
8 int main(){
9 int n, f;
10 scanf("%d", &n);
11 f = fact(n);
12 printf("Factorial(%d) = %d\n
",n,f);
13 return 0;
14 }

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Recursion in C
Example of a Recursive Function Factorial Function

1 #include<stdio.h> The function fact takes an


2
integer n as argument and
3 int fact(int n){
4 if (n==0) return 1;
returns the factorial of n.
5 else return n*fact(n-1);
6 }
7
8 int main(){
9 int n, f;
10 scanf("%d", &n);
11 f = fact(n);
12 printf("Factorial(%d) = %d\n
",n,f);
13 return 0;
14 }

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Recursion in C
Example of a Recursive Function Factorial Function

1 #include<stdio.h> The function fact takes an


2
integer n as argument and
3 int fact(int n){
4 if (n==0) return 1;
returns the factorial of n.
5 else return n*fact(n-1); Calls to function fact:
6 } - First Call: Line 11 (from
7
main function).
8 int main(){ - Subsequent Calls: Line 5
9 int n, f;
(from fact function).
10 scanf("%d", &n);
11 f = fact(n);
12 printf("Factorial(%d) = %d\n
",n,f);
13 return 0;
14 }

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Recursion in C
Example of a Recursive Function Factorial Function

1 #include<stdio.h> The function fact takes an


2
integer n as argument and
3 int fact(int n){
4 if (n==0) return 1;
returns the factorial of n.
5 else return n*fact(n-1); Calls to function fact:
6 } - First Call: Line 11 (from
7
main function).
8 int main(){ - Subsequent Calls: Line 5
9 int n, f;
(from fact function).
10 scanf("%d", &n);
11 f = fact(n); Argument of fact decreasing
12 printf("Factorial(%d) = %d\n in successive calls.
",n,f);
13 return 0;
14 }

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Recursion in C
Example of a Recursive Function Factorial Function

1 #include<stdio.h> The function fact takes an


2
integer n as argument and
3 int fact(int n){
4 if (n==0) return 1;
returns the factorial of n.
5 else return n*fact(n-1); Calls to function fact:
6 } - First Call: Line 11 (from
7
main function).
8 int main(){ - Subsequent Calls: Line 5
9 int n, f;
(from fact function).
10 scanf("%d", &n);
11 f = fact(n); Argument of fact decreasing
12 printf("Factorial(%d) = %d\n in successive calls.
",n,f);
13 return 0;
How many calls are made,
14 } say when n = 6?

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Recursion in C
Example of a Recursive Function Factorial Function

1 #include<stdio.h> The function fact takes an


2
integer n as argument and
3 int fact(int n){
4 if (n==0) return 1;
returns the factorial of n.
5 else return n*fact(n-1); Calls to function fact:
6 } - First Call: Line 11 (from
7
main function).
8 int main(){ - Subsequent Calls: Line 5
9 int n, f;
(from fact function).
10 scanf("%d", &n);
11 f = fact(n); Argument of fact decreasing
12 printf("Factorial(%d) = %d\n in successive calls.
",n,f);
13 return 0;
How many calls are made,
14 } say when n = 6?
7 calls.

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Recursion in C
Memory Usage by Recursive Functions

Whenever a call is made to a


function, space is reserved in
the stack for the function
arguments and the variables
declared inside the function.

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Recursion in C
Memory Usage by Recursive Functions

Whenever a call is made to a


function, space is reserved in
the stack for the function
arguments and the variables
declared inside the function.
For recursive functions,
separate space is created for
each call to the function.

Order of Execution: fact(3) = 3*fact(2)= 3*(2*fact(1))=


3*(2*(1*fact(0)))= 3*(2*(1*1))= 3*(2*1)= 3*2 = 6
Recursion in C

Recursion in C
Memory Usage by Recursive Functions

fact(0)

Whenever a call is made to a


fact(1)
function, space is reserved in
the stack for the function
arguments and the variables fact(2)
declared inside the function.
fact(3)
For recursive functions,
separate space is created for
main
each call to the function.

Order of Execution: fact(3) = 3*fact(2)= 3*(2*fact(1))=


3*(2*(1*fact(0)))= 3*(2*(1*1))= 3*(2*1)= 3*2 = 6
Recursion in C

Recursion in C
Memory Usage by Recursive Functions

fact(0)

Whenever a call is made to a


fact(1)
function, space is reserved in
the stack for the function
arguments and the variables fact(2)
declared inside the function.
fact(3)
For recursive functions,
separate space is created for 3
main
each call to the function. n f

Order of Execution: fact(3) = 3*fact(2)= 3*(2*fact(1))=


3*(2*(1*fact(0)))= 3*(2*(1*1))= 3*(2*1)= 3*2 = 6
Recursion in C

Recursion in C
Memory Usage by Recursive Functions

fact(0)

Whenever a call is made to a


fact(1)
function, space is reserved in
the stack for the function
arguments and the variables fact(2)
declared inside the function. 3
fact(3)
For recursive functions, n
separate space is created for 3
main
each call to the function. n f

Order of Execution: fact(3) = 3*fact(2)= 3*(2*fact(1))=


3*(2*(1*fact(0)))= 3*(2*(1*1))= 3*(2*1)= 3*2 = 6
Recursion in C

Recursion in C
Memory Usage by Recursive Functions

fact(0)

Whenever a call is made to a


fact(1)
function, space is reserved in
the stack for the function 2
arguments and the variables fact(2)
n
declared inside the function. 3
fact(3)
For recursive functions, n
separate space is created for 3
main
each call to the function. n f

Order of Execution: fact(3) = 3*fact(2)= 3*(2*fact(1))=


3*(2*(1*fact(0)))= 3*(2*(1*1))= 3*(2*1)= 3*2 = 6
Recursion in C

Recursion in C
Memory Usage by Recursive Functions

fact(0)

Whenever a call is made to a 2


fact(1)
function, space is reserved in n
the stack for the function 2
arguments and the variables fact(2)
n
declared inside the function. 3
fact(3)
For recursive functions, n
separate space is created for 3
main
each call to the function. n f

Order of Execution: fact(3) = 3*fact(2)= 3*(2*fact(1))=


3*(2*(1*fact(0)))= 3*(2*(1*1))= 3*(2*1)= 3*2 = 6
Recursion in C

Recursion in C
Memory Usage by Recursive Functions

0
fact(0)
n
Whenever a call is made to a 2
fact(1)
function, space is reserved in n
the stack for the function 2
arguments and the variables fact(2)
n
declared inside the function. 3
fact(3)
For recursive functions, n
separate space is created for 3
main
each call to the function. n f

Order of Execution: fact(3) = 3*fact(2)= 3*(2*fact(1))=


3*(2*(1*fact(0)))= 3*(2*(1*1))= 3*(2*1)= 3*2 = 6
Recursion in C

Recursion in C
Memory Usage by Recursive Functions

0
fact(0)
n
Whenever a call is made to a 2
fact(1)
function, space is reserved in n
the stack for the function 2
arguments and the variables fact(2)
n
declared inside the function. 3
fact(3)
For recursive functions, n
separate space is created for 3
main
each call to the function. n f
Order of
Function Calls
Order of Execution: fact(3) = 3*fact(2)= 3*(2*fact(1))=
3*(2*(1*fact(0)))= 3*(2*(1*1))= 3*(2*1)= 3*2 = 6
Recursion in C

Recursion in C
Memory Usage by Recursive Functions

Return Values
0
fact(0) 1
n
Whenever a call is made to a 2
fact(1) 1
function, space is reserved in n
the stack for the function 2
arguments and the variables fact(2) 2
n
declared inside the function. 3
fact(3) 6
For recursive functions, n
separate space is created for 3
main
each call to the function. n f
Order of
Function Calls
Order of Execution: fact(3) = 3*fact(2)= 3*(2*fact(1))=
3*(2*(1*fact(0)))= 3*(2*(1*1))= 3*(2*1)= 3*2 = 6
Recursion in C

Recursion in C
Memory Usage by Recursive Functions

Return Values
0
fact(0) 1
n
Whenever a call is made to a 2
fact(1) 1
function, space is reserved in n
the stack for the function 2
arguments and the variables fact(2) 2
n
declared inside the function. 3
fact(3) 6
For recursive functions, n
separate space is created for 3 6
main
each call to the function. n f
Order of
Function Calls

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Recursion in C
Memory Usage by Recursive Functions

Return Values
0
fact(0) 1
n
Whenever a call is made to a 2
fact(1) 1
function, space is reserved in n
the stack for the function 2
arguments and the variables fact(2) 2
n
declared inside the function. 3
fact(3) 6
For recursive functions, n
separate space is created for 3 6
main
each call to the function. n f
Order of
Function Calls
Order of Execution: fact(3) = 3*fact(2)= 3*(2*fact(1))=
3*(2*(1*fact(0)))= 3*(2*(1*1))= 3*(2*1)= 3*2 = 6
Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A
Recursion in C

Recursion in C
Example n choose k (Definition)

Binomial Coefficient (n choose k)


Non-recursive Definition
 
n n!
=
k k! (n k)!

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Recursion in C
Example n choose k (Definition)

Binomial Coefficient (n choose k)


Non-recursive Definition
 
n n!
=
k k! (n k)!

Recursive Definition
     
n n1 n1
= + for 1 k n 1
k k 1 k
   
n n
= = 1 for n 0 (Base Case)
0 n

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Recursion in C
Example n choose k (Definition)

Binomial Coefficient (n choose k)


Non-recursive Definition
 
n n!
=
k k! (n k)!

Recursive Definition
     
n n1 n1
= + for 1 k n 1
k k 1 k
   
n n
= = 1 for n 0 (Base Case)
0 n
Note: In each recursive step, value of n decreases. Value of k may
or may not decrease. Recursion stops when n = k or k = 0.
Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A
Recursion in C

Recursion in C
Example n choose k (Program)

1 #include<stdio.h>
2
3 int choose(int n, int k){
4 if ((n == k) || (k == 0))
5 return 1;
6 else
7 return (choose(n-1,k-1) +
choose(n-1,k));
8 }
9
10 int main(){
11 int n,k;
12 scanf("%d",&n);
13 scanf("%d",&k);
14 printf("%d\n",choose(n,k));
15 return 0;
16 }

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Recursion in C
Example n choose k (Program)

1 #include<stdio.h>
2 Notethat to obtain the value
3 int choose(int n, int k){ of kn , two recursive calls
4 if ((n == k) || (k == 0))
5 return 1;
needto be made one to
n1 n1
6 else k1 and one to k .
7 return (choose(n-1,k-1) +
choose(n-1,k));
8 }
9
10 int main(){
11 int n,k;
12 scanf("%d",&n);
13 scanf("%d",&k);
14 printf("%d\n",choose(n,k));
15 return 0;
16 }

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Recursion in C
Example n choose k (Program)

1 #include<stdio.h>
2 Notethat to obtain the value
3 int choose(int n, int k){ of kn , two recursive calls
4 if ((n == k) || (k == 0))
5 return 1;
needto be made one to
n1 n1
6 else k1 and one to k .
7 return (choose(n-1,k-1) + Known as double recursion.
choose(n-1,k));
8 }
9
10 int main(){
11 int n,k;
12 scanf("%d",&n);
13 scanf("%d",&k);
14 printf("%d\n",choose(n,k));
15 return 0;
16 }

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Recursion in C
Example n choose k (Program)

1 #include<stdio.h>
2 Notethat to obtain the value
3 int choose(int n, int k){ of kn , two recursive calls
4 if ((n == k) || (k == 0))
5 return 1;
needto be made one to
n1 n1
6 else k1 and one to k .
7 return (choose(n-1,k-1) + Known as double recursion.
choose(n-1,k));
8 } How many calls to the
9 function choose is made when
10 int main(){ n=6 and k=3?
11 int n,k;
12 scanf("%d",&n);
13 scanf("%d",&k);
14 printf("%d\n",choose(n,k));
15 return 0;
16 }

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Recursion in C
Example n choose k (Program)

1 #include<stdio.h>
2 Notethat to obtain the value
3 int choose(int n, int k){ of kn , two recursive calls
4 if ((n == k) || (k == 0))
5 return 1;
needto be made one to
n1 n1
6 else k1 and one to k .
7 return (choose(n-1,k-1) + Known as double recursion.
choose(n-1,k));
8 } How many calls to the
9 function choose is made when
10 int main(){ n=6 and k=3?
11 int n,k;
12 scanf("%d",&n); 37 calls!
13 scanf("%d",&k); No. of calls grow very fast
14 printf("%d\n",choose(n,k));
15 return 0;
(exponentially) with
16 } increasing values of n and k.

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Recursion in C
Example n choose k (Function Call Tree)

A Tree Structure representing the function call choose(5,2)

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Recursion in C
Example n choose k (Function Call Tree)

A Tree Structure representing the function call choose(5,2)


(5,2)

(4,1) (4,2)

(3,0) (3,1)
(3,1) (3,2)
1 (2,0) (2,1)
(2,0) (2,1) (2,1) (2,2)
1 (1,0) (1,1)
1 (1,0) (1,1) (1,0) (1,1) 1
1 1
1 1 1 1

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Recursion in C
Example n choose k (Order of Execution)

For n = 4 and k = 2.

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Recursion in C
Example n choose k (Order of Execution)

For n = 4 and k = 2.
choose(4,2) = choose(3,1) + choose(3,2)

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Recursion in C
Example n choose k (Order of Execution)

For n = 4 and k = 2.
choose(4,2) = choose(3,1) + choose(3,2)
= choose(2,0) + choose(2,1) + choose(3,2)

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Recursion in C
Example n choose k (Order of Execution)

For n = 4 and k = 2.
choose(4,2) = choose(3,1) + choose(3,2)
= choose(2,0)+ choose(2,1) + choose(3,2)
= 1 + choose(2,1) + choose(3,2)

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Recursion in C
Example n choose k (Order of Execution)

For n = 4 and k = 2.
choose(4,2) = choose(3,1) + choose(3,2)
= choose(2,0) + choose(2,1) + choose(3,2)
= 1+ choose(2,1) + choose(3,2)
= 1+ choose(1,0) + choose(1,1) + choose(3,2)
= 1+ 1 + choose(1,1) + choose(3,2)
= 1+ 1 + 1 + choose(3,2)
= 1+ 1 + 1 + choose(2,1) + choose(2,2)
= 1+ 1 + 1 + choose(1,0) + choose(1,1)
+ choose(2,2)
= 1 + 1 + 1 + 1 + choose(1,1) + choose(2,2)

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Recursion in C
Example n choose k (Order of Execution)

For n = 4 and k = 2.
choose(4,2) = choose(3,1) + choose(3,2)
= choose(2,0) + choose(2,1) + choose(3,2)
= 1+ choose(2,1) + choose(3,2)
= 1+ choose(1,0) + choose(1,1) + choose(3,2)
= 1+ 1 + choose(1,1) + choose(3,2)
= 1+ 1 + 1 + choose(3,2)
= 1+ 1 + 1 + choose(2,1) + choose(2,2)
= 1+ 1 + 1 + choose(1,0) + choose(1,1)
+ choose(2,2)
= 1 + 1 + 1 + 1 + choose(1,1) + choose(2,2)
= 1 + 1 + 1 + 1 + 1 + choose(2,2)

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Recursion in C
Example n choose k (Order of Execution)

For n = 4 and k = 2.
choose(4,2) = choose(3,1) + choose(3,2)
= choose(2,0) + choose(2,1) + choose(3,2)
= 1+ choose(2,1) + choose(3,2)
= 1+ choose(1,0) + choose(1,1) + choose(3,2)
= 1+ 1 + choose(1,1) + choose(3,2)
= 1+ 1 + 1 + choose(3,2)
= 1+ 1 + 1 + choose(2,1) + choose(2,2)
= 1+ 1 + 1 + choose(1,0) + choose(1,1)
+ choose(2,2)
= 1 + 1 + 1 + 1 + choose(1,1) + choose(2,2)
= 1 + 1 + 1 + 1 + 1 + choose(2,2)
= 1+1+1+1+1+1

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Recursion in C
Example n choose k (Order of Execution)

For n = 4 and k = 2.
choose(4,2) = choose(3,1) + choose(3,2)
= choose(2,0) + choose(2,1) + choose(3,2)
= 1+ choose(2,1) + choose(3,2)
= 1+ choose(1,0) + choose(1,1) + choose(3,2)
= 1+ 1 + choose(1,1) + choose(3,2)
= 1+ 1 + 1 + choose(3,2)
= 1+ 1 + 1 + choose(2,1) + choose(2,2)
= 1+ 1 + 1 + choose(1,0) + choose(1,1)
+ choose(2,2)
= 1 + 1 + 1 + 1 + choose(1,1) + choose(2,2)
= 1 + 1 + 1 + 1 + 1 + choose(2,2)
= 1+1+1+1+1+1
= 6

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Recursion in C
Advantages and Disadvantages

Advantages

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Recursion in C
Advantages and Disadvantages

Advantages
- Elegant. Solution is cleaner.

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Recursion in C
Advantages and Disadvantages

Advantages
- Elegant. Solution is cleaner.
- Fewer variables.

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Recursion in C
Advantages and Disadvantages

Advantages
- Elegant. Solution is cleaner.
- Fewer variables.
- Once the recursive definition is figured out, program is easy to
implement.
Disadvantages

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Recursion in C
Advantages and Disadvantages

Advantages
- Elegant. Solution is cleaner.
- Fewer variables.
- Once the recursive definition is figured out, program is easy to
implement.
Disadvantages
- Debugging can be considerably more difficult.

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Recursion in C
Advantages and Disadvantages

Advantages
- Elegant. Solution is cleaner.
- Fewer variables.
- Once the recursive definition is figured out, program is easy to
implement.
Disadvantages
- Debugging can be considerably more difficult.
- Figuring out the logic of the recursive function is not easy
sometimes.

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Recursion in C
Advantages and Disadvantages

Advantages
- Elegant. Solution is cleaner.
- Fewer variables.
- Once the recursive definition is figured out, program is easy to
implement.
Disadvantages
- Debugging can be considerably more difficult.
- Figuring out the logic of the recursive function is not easy
sometimes.
- In general, can be inefficient (requires more time and space).

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Example Reversing a String


Recursive Definition

String Reverse
Recursive Definition:
- reverse(aw)= reverse(w)a
- where w is a string and a is a single character.
Base Case:
- reverse(w)= w
- when w is the empty string (string of length 0).

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Example Reversing a String


Program

1 #include <stdio.h>
2 void reverse(){
3 char c;
4 scanf("%c",&c);
5 if( c != \n){
6 reverse();
7 printf("%c",c);
8 }
9 }
10
11 int main(){
12 reverse();
13 printf("\n");
14 return 0;
15 }

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Recap

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Recap

What is recursion?

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Recap

What is recursion?
Two components:

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Recap

What is recursion?
Two components:
- recursive definition, and

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Recap

What is recursion?
Two components:
- recursive definition, and
- base case.

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Recap

What is recursion?
Two components:
- recursive definition, and
- base case.
Function stack.

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Recap

What is recursion?
Two components:
- recursive definition, and
- base case.
Function stack.
Advantages and disadvantages.

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Finding Maximum Element in an Array


Iterative Solution

Write a function that takes an integer array and the size of


the array as argument and returns the maximum element.

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Finding Maximum Element in an Array


Iterative Solution

Write a function that takes an integer array and the size of


the array as argument and returns the maximum element.

1 int iterative_max(int *ar, int n)


{
2 int i, max = ar[0];
3 for (i=1; i<n; i++){
4 if (max < ar[i])
5 max = ar[i];
6 }
7 return max;
8 }

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Finding Maximum Element in an Array


Iterative Solution

Write a function that takes an integer array and the size of


the array as argument and returns the maximum element.

1 int iterative_max(int *ar, int n)


{
2 int i, max = ar[0]; - Number of steps: n-1.
3 for (i=1; i<n; i++){
4 if (max < ar[i])
5 max = ar[i];
6 }
7 return max;
8 }

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Finding Maximum Element in an Array


Iterative Solution

Write a function that takes an integer array and the size of


the array as argument and returns the maximum element.

1 int iterative_max(int *ar, int n)


{
2 int i, max = ar[0]; - Number of steps: n-1.
3 for (i=1; i<n; i++){
4 if (max < ar[i]) - Space used: 2 integer
5 max = ar[i]; variables (ar and n were part
6 } of the input).
7 return max;
8 }

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Finding Maximum Element in an Array


Recursive Solution I (Definition and Program)

Recursive Definition:

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Finding Maximum Element in an Array


Recursive Solution I (Definition and Program)

Recursive Definition:
- r max1({a0 , a1 , . . . , an1 }, n) = max(a0 , r max1({a1 , . . . , an1 }, n 1))

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Finding Maximum Element in an Array


Recursive Solution I (Definition and Program)

Recursive Definition:
- r max1({a0 , a1 , . . . , an1 }, n) = max(a0 , r max1({a1 , . . . , an1 }, n 1))
- r max1({a0 }, 1) = a0

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Finding Maximum Element in an Array


Recursive Solution I (Definition and Program)

Recursive Definition:
- r max1({a0 , a1 , . . . , an1 }, n) = max(a0 , r max1({a1 , . . . , an1 }, n 1))
- r max1({a0 }, 1) = a0

1 int r_max1(int *ar, int n){


2 if (n==1) return *ar;
3 else return max(*ar,r_max1(ar+1,n-1));
4 }
5
6 int max(int a, int b){
7 if (a>b) return a;
8 else return b;
9 }

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Finding Maximum Element in an Array


Recursive Solution I (Function Stack)

1 int r_max1(int *ar, int n){


2 if (n==1) return *ar;
3 else return max(*ar,r_max1(
ar+1,n-1));
4 }
5
6 int max(int a, int b){
7 if (a>b) return a;
8 else return b;
9 }

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Finding Maximum Element in an Array


Recursive Solution I (Function Stack)

ar 48 7 5 11 7
Addresses 48 52 56 60
1 int r_max1(int *ar, int n){
2 if (n==1) return *ar;
3 else return max(*ar,r_max1(
ar+1,n-1));
4 }
5
6 int max(int a, int b){
7 if (a>b) return a;
8 else return b;
9 }
Recursion in C

Finding Maximum Element in an Array


Recursive Solution I (Function Stack)

ar 48 7 5 11 7
Addresses 48 52 56 60
1 int r_max1(int *ar, int n){
2 if (n==1) return *ar;
3 else return max(*ar,r_max1(
ar+1,n-1));
4 }
5
6 int max(int a, int b){
7 if (a>b) return a;
8 else return b;
9 }
48 4
r max1(48,4)
ar n
Recursion in C

Finding Maximum Element in an Array


Recursive Solution I (Function Stack)

ar 48 7 5 11 7
Addresses 48 52 56 60
1 int r_max1(int *ar, int n){
2 if (n==1) return *ar;
3 else return max(*ar,r_max1(
ar+1,n-1));
4 }
5
6 int max(int a, int b){
7 if (a>b) return a; 52 3
8 else return b; r max1(52,3)
ar n
9 }
48 4
r max1(48,4)
ar n
Recursion in C

Finding Maximum Element in an Array


Recursive Solution I (Function Stack)

ar 48 7 5 11 7
Addresses 48 52 56 60
1 int r_max1(int *ar, int n){
2 if (n==1) return *ar;
3 else return max(*ar,r_max1(
ar+1,n-1));
4 }
5
56 2
r max1(56,2)
6 int max(int a, int b){ ar n
7 if (a>b) return a; 52 3
8 else return b; r max1(52,3)
ar n
9 }
48 4
r max1(48,4)
ar n
Recursion in C

Finding Maximum Element in an Array


Recursive Solution I (Function Stack)

ar 48 7 5 11 7
Addresses 48 52 56 60
1 int r_max1(int *ar, int n){
2 if (n==1) return *ar;
3 else return max(*ar,r_max1( 60 1
r max1(60,1)
ar+1,n-1)); ar n
4 }
5
56 2
r max1(56,2)
6 int max(int a, int b){ ar n
7 if (a>b) return a; 52 3
8 else return b; r max1(52,3)
ar n
9 }
48 4
r max1(48,4)
ar n
Recursion in C

Finding Maximum Element in an Array


Recursive Solution I (Function Stack)

ar 48 7 5 11 7
Addresses 48 52 56 60
1 int r_max1(int *ar, int n){
2 if (n==1) return *ar; Return Values
3 else return max(*ar,r_max1( 60 1
r max1(60,1)
ar+1,n-1)); ar n
4 }
5
56 2
r max1(56,2)
6 int max(int a, int b){ ar n
7 if (a>b) return a; 52 3
8 else return b; r max1(52,3)
ar n
9 }
48 4
r max1(48,4)
ar n
Recursion in C

Finding Maximum Element in an Array


Recursive Solution I (Function Stack)

ar 48 7 5 11 7
Addresses 48 52 56 60
1 int r_max1(int *ar, int n){
2 if (n==1) return *ar; Return Values
3 else return max(*ar,r_max1( 60 1
ar+1,n-1));
r max1(60,1) 7
ar n
4 }
5
56 2
r max1(56,2)
6 int max(int a, int b){ ar n
7 if (a>b) return a; 52 3
8 else return b; r max1(52,3)
ar n
9 }
48 4
r max1(48,4)
ar n
Recursion in C

Finding Maximum Element in an Array


Recursive Solution I (Function Stack)

ar 48 7 5 11 7
Addresses 48 52 56 60
1 int r_max1(int *ar, int n){
2 if (n==1) return *ar; Return Values
3 else return max(*ar,r_max1( 60 1
ar+1,n-1));
r max1(60,1) 7
ar n
4 }
5
56 2
r max1(56,2) 11
6 int max(int a, int b){ ar n
7 if (a>b) return a; 52 3
8 else return b; r max1(52,3)
ar n
9 }
48 4
r max1(48,4)
ar n
Recursion in C

Finding Maximum Element in an Array


Recursive Solution I (Function Stack)

ar 48 7 5 11 7
Addresses 48 52 56 60
1 int r_max1(int *ar, int n){
2 if (n==1) return *ar; Return Values
3 else return max(*ar,r_max1( 60 1
ar+1,n-1));
r max1(60,1) 7
ar n
4 }
5
56 2
r max1(56,2) 11
6 int max(int a, int b){ ar n
7 if (a>b) return a; 52 3
8 else return b; r max1(52,3) 11
ar n
9 }
48 4
r max1(48,4)
ar n
Recursion in C

Finding Maximum Element in an Array


Recursive Solution I (Function Stack)

ar 48 7 5 11 7
Addresses 48 52 56 60
1 int r_max1(int *ar, int n){
2 if (n==1) return *ar; Return Values
3 else return max(*ar,r_max1( 60 1
ar+1,n-1));
r max1(60,1) 7
ar n
4 }
5
56 2
r max1(56,2) 11
6 int max(int a, int b){ ar n
7 if (a>b) return a; 52 3
8 else return b; r max1(52,3) 11
ar n
9 }
48 4
r max1(48,4) 11
ar n

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Finding Maximum Element in an Array


Recursive Solution I (Function Stack)

ar 48 7 5 11 7
Addresses 48 52 56 60
1 int r_max1(int *ar, int n){
2 if (n==1) return *ar; Return Values
3 else return max(*ar,r_max1( 60 1
ar+1,n-1));
r max1(60,1) 7
ar n
4 }
5
56 2
r max1(56,2) 11
6 int max(int a, int b){ ar n
7 if (a>b) return a; 52 3
8 else return b; r max1(52,3) 11
ar n
9 }
48 4
r max1(48,4) 11
ar n
Note that the function r_max1 makes one call to itself in the
function definition.
Time is about n and space is equivalent to stack depth (which
is n).
Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A
Recursion in C

Finding Maximum Element in an Array


Recursive Solution II (Definition)

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Finding Maximum Element in an Array


Recursive Solution II (Definition)

If array size is 1, return the element.

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Finding Maximum Element in an Array


Recursive Solution II (Definition)

If array size is 1, return the element.


Otherwise, divide the array into two halves.

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Finding Maximum Element in an Array


Recursive Solution II (Definition)

If array size is 1, return the element.


Otherwise, divide the array into two halves.
Compute maximum of both the halves.

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Finding Maximum Element in an Array


Recursive Solution II (Definition)

If array size is 1, return the element.


Otherwise, divide the array into two halves.
Compute maximum of both the halves.
Return maximum of these two values.
Recursive Definition:

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Finding Maximum Element in an Array


Recursive Solution II (Definition)

If array size is 1, return the element.


Otherwise, divide the array into two halves.
Compute maximum of both the halves.
Return maximum of these two values.
Recursive Definition:
- r max2({a0 , a1 , . . . , an1 }, n) =
max(r max2({a0 , . . . , an/21 }, n/2), r max2({an/2 , . . . , an1 }, (n + 1)/2))

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Finding Maximum Element in an Array


Recursive Solution II (Definition)

If array size is 1, return the element.


Otherwise, divide the array into two halves.
Compute maximum of both the halves.
Return maximum of these two values.
Recursive Definition:
- r max2({a0 , a1 , . . . , an1 }, n) =
max(r max2({a0 , . . . , an/21 }, n/2), r max2({an/2 , . . . , an1 }, (n + 1)/2))
- r max2({a0 }, 1) = a0

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Finding Maximum Element in an Array


Recursive Solution II (Program)

1 int max(int a, int b){


2 if (a>b) return a;
3 else return b;
4 }
5 int r_max2(int *ar, int n){
6 if (n==1) return *ar;
7 else return max(r_max2(ar,n
/2),r_max2(ar+(n/2),(n
+1)/2));
8 }

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Finding Maximum Element in an Array


Recursive Solution II (Program)

1 int max(int a, int b){


2 if (a>b) return a;
3 else return b;
4 }
5 int r_max2(int *ar, int n){
6 if (n==1) return *ar;
7 else return max(r_max2(ar,n
/2),r_max2(ar+(n/2),(n
+1)/2));
8 }

The function r_max2


makes two calls to itself
in the function definition.

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Finding Maximum Element in an Array


Recursive Solution II (Program)

ar 48 7 5 11 7
Addresses 48 52 56 60
1 int max(int a, int b){
2 if (a>b) return a;
3 else return b;
4 }
5 int r_max2(int *ar, int n){
6 if (n==1) return *ar;
7 else return max(r_max2(ar,n
/2),r_max2(ar+(n/2),(n
+1)/2));
8 }

The function r_max2


makes two calls to itself
in the function definition.

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Finding Maximum Element in an Array


Recursive Solution II (Program)

ar 48 7 5 11 7
Addresses 48 52 56 60
1 int max(int a, int b){
2 if (a>b) return a; Function Call Tree to r_max2 for
3 else return b; the above array.
4 }
5 int r_max2(int *ar, int n){
6 if (n==1) return *ar;
7 else return max(r_max2(ar,n
/2),r_max2(ar+(n/2),(n
+1)/2));
8 }

The function r_max2


makes two calls to itself
in the function definition.

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Finding Maximum Element in an Array


Recursive Solution II (Program)

ar 48 7 5 11 7
Addresses 48 52 56 60
1 int max(int a, int b){
2 if (a>b) return a; Function Call Tree to r_max2 for
3 else return b; the above array.
4 } (48,4)
5 int r_max2(int *ar, int n){
6 if (n==1) return *ar;
7 else return max(r_max2(ar,n (48,2) (56,2)
/2),r_max2(ar+(n/2),(n
+1)/2));
(48,1) (52,1) (56,1) (60,1)
8 }

The function r_max2


makes two calls to itself
in the function definition.

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Finding Maximum Element in an Array


Recursive Solution II (Program)

ar 48 7 5 11 7
Addresses 48 52 56 60
1 int max(int a, int b){
2 if (a>b) return a; Function Call Tree to r_max2 for
3 else return b; the above array.
4 } (48,4)
5 int r_max2(int *ar, int n){
6 if (n==1) return *ar;
7 else return max(r_max2(ar,n (48,2) (56,2)
/2),r_max2(ar+(n/2),(n
+1)/2));
(48,1) (52,1) (56,1) (60,1)
8 }
- Number of function calls:
The function r_max2 2n-1
makes two calls to itself (constant time per call).
in the function definition.

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Finding Maximum Element in an Array


Recursive Solution II (Program)

ar 48 7 5 11 7
Addresses 48 52 56 60
1 int max(int a, int b){
2 if (a>b) return a; Function Call Tree to r_max2 for
3 else return b; the above array.
4 } (48,4)
5 int r_max2(int *ar, int n){
6 if (n==1) return *ar;
7 else return max(r_max2(ar,n (48,2) (56,2)
/2),r_max2(ar+(n/2),(n
+1)/2));
(48,1) (52,1) (56,1) (60,1)
8 }
- Number of function calls:
The function r_max2 2n-1
makes two calls to itself (constant time per call).
in the function definition. - Stack Depth: log (n)
(space used).
Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A
Recursion in C

Searching an Element in an Array

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Searching an Element in an Array


How do we search for an element in an array?

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Searching an Element in an Array


How do we search for an element in an array?
- Check if the element is present in each cell of the array.

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Searching an Element in an Array


How do we search for an element in an array?
- Check if the element is present in each cell of the array.
How many steps does the above algorithm take?

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Searching an Element in an Array


How do we search for an element in an array?
- Check if the element is present in each cell of the array.
How many steps does the above algorithm take?
- About n (where n is the size of the array).

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Searching an Element in an Array


How do we search for an element in an array?
- Check if the element is present in each cell of the array.
How many steps does the above algorithm take?
- About n (where n is the size of the array).
Now, suppose the array is sorted (say in increasing order)?

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Searching an Element in an Array


How do we search for an element in an array?
- Check if the element is present in each cell of the array.
How many steps does the above algorithm take?
- About n (where n is the size of the array).
Now, suppose the array is sorted (say in increasing order)?
Can you do better than n?

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Searching an Element in an Array


How do we search for an element in an array?
- Check if the element is present in each cell of the array.
How many steps does the above algorithm take?
- About n (where n is the size of the array).
Now, suppose the array is sorted (say in increasing order)?
Can you do better than n?
We will use the fact that the array is sorted, to discard some
comparisons (in fact many).

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Searching an Element in an Array


How do we search for an element in an array?
- Check if the element is present in each cell of the array.
How many steps does the above algorithm take?
- About n (where n is the size of the array).
Now, suppose the array is sorted (say in increasing order)?
Can you do better than n?
We will use the fact that the array is sorted, to discard some
comparisons (in fact many).
Idea (Binary Search):

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Searching an Element in an Array


How do we search for an element in an array?
- Check if the element is present in each cell of the array.
How many steps does the above algorithm take?
- About n (where n is the size of the array).
Now, suppose the array is sorted (say in increasing order)?
Can you do better than n?
We will use the fact that the array is sorted, to discard some
comparisons (in fact many).
Idea (Binary Search):
- Let ar be the given array of size n, and we want to search for
the element elt in ar.

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Searching an Element in an Array


How do we search for an element in an array?
- Check if the element is present in each cell of the array.
How many steps does the above algorithm take?
- About n (where n is the size of the array).
Now, suppose the array is sorted (say in increasing order)?
Can you do better than n?
We will use the fact that the array is sorted, to discard some
comparisons (in fact many).
Idea (Binary Search):
- Let ar be the given array of size n, and we want to search for
the element elt in ar.
- We check if elt is the middle element in ar.

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Searching an Element in an Array


How do we search for an element in an array?
- Check if the element is present in each cell of the array.
How many steps does the above algorithm take?
- About n (where n is the size of the array).
Now, suppose the array is sorted (say in increasing order)?
Can you do better than n?
We will use the fact that the array is sorted, to discard some
comparisons (in fact many).
Idea (Binary Search):
- Let ar be the given array of size n, and we want to search for
the element elt in ar.
- We check if elt is the middle element in ar.
- If yes, we are done. Otherwise, if elt is smaller, what can we
say?

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Searching an Element in an Array


How do we search for an element in an array?
- Check if the element is present in each cell of the array.
How many steps does the above algorithm take?
- About n (where n is the size of the array).
Now, suppose the array is sorted (say in increasing order)?
Can you do better than n?
We will use the fact that the array is sorted, to discard some
comparisons (in fact many).
Idea (Binary Search):
- Let ar be the given array of size n, and we want to search for
the element elt in ar.
- We check if elt is the middle element in ar.
- If yes, we are done. Otherwise, if elt is smaller, what can we
say?
- elt must be present in the first half of the array!

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Searching an Element in an Array


How do we search for an element in an array?
- Check if the element is present in each cell of the array.
How many steps does the above algorithm take?
- About n (where n is the size of the array).
Now, suppose the array is sorted (say in increasing order)?
Can you do better than n?
We will use the fact that the array is sorted, to discard some
comparisons (in fact many).
Idea (Binary Search):
- Let ar be the given array of size n, and we want to search for
the element elt in ar.
- We check if elt is the middle element in ar.
- If yes, we are done. Otherwise, if elt is smaller, what can we
say?
- elt must be present in the first half of the array!
- Hence after one comparison we have eliminated one half of the
array.
Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A
Recursion in C

Binary Search
Example

Consider the following array: {2,4,5,7,10,11,15,20,25,30,35}


Suppose we want to search for the element 17 in the array.

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Binary Search
Example

Consider the following array: {2,4,5,7,10,11,15,20,25,30,35}


Suppose we want to search for the element 17 in the array.
- Compare 17 with the middle element, 11.
2 4 5 7 10 11 15 20 25 30 35

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Binary Search
Example

Consider the following array: {2,4,5,7,10,11,15,20,25,30,35}


Suppose we want to search for the element 17 in the array.
- Compare 17 with the middle element, 11.
2 4 5 7 10 11 15 20 25 30 35
- Consider the 2nd half since 17 is greater.
2 4 5 7 10 11 15 20 25 30 35

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Binary Search
Example

Consider the following array: {2,4,5,7,10,11,15,20,25,30,35}


Suppose we want to search for the element 17 in the array.
- Compare 17 with the middle element, 11.
2 4 5 7 10 11 15 20 25 30 35
- Consider the 2nd half since 17 is greater.
2 4 5 7 10 11 15 20 25 30 35
- Compare 17 with the middle element, 25.
15 20 25 30 35

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Binary Search
Example

Consider the following array: {2,4,5,7,10,11,15,20,25,30,35}


Suppose we want to search for the element 17 in the array.
- Compare 17 with the middle element, 11.
2 4 5 7 10 11 15 20 25 30 35
- Consider the 2nd half since 17 is greater.
2 4 5 7 10 11 15 20 25 30 35
- Compare 17 with the middle element, 25.
15 20 25 30 35
- Consider the 1st half since 17 is smaller.
15 20 25 30 35

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Binary Search
Example

Consider the following array: {2,4,5,7,10,11,15,20,25,30,35}


Suppose we want to search for the element 17 in the array.
- Compare 17 with the middle element, 11.
2 4 5 7 10 11 15 20 25 30 35
- Consider the 2nd half since 17 is greater.
2 4 5 7 10 11 15 20 25 30 35
- Compare 17 with the middle element, 25.
15 20 25 30 35
- Consider the 1st half since 17 is smaller.
15 20 25 30 35
- Compare 17 with the middle element, 15.
15 20

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Binary Search
Example

Consider the following array: {2,4,5,7,10,11,15,20,25,30,35}


Suppose we want to search for the element 17 in the array.
- Compare 17 with the middle element, 11.
2 4 5 7 10 11 15 20 25 30 35
- Consider the 2nd half since 17 is greater.
2 4 5 7 10 11 15 20 25 30 35
- Compare 17 with the middle element, 25.
15 20 25 30 35
- Consider the 1st half since 17 is smaller.
15 20 25 30 35
- Compare 17 with the middle element, 15.
15 20
- Consider the 2nd half since 17 is greater.
15 20

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Binary Search
Example

Consider the following array: {2,4,5,7,10,11,15,20,25,30,35}


Suppose we want to search for the element 17 in the array.
- Compare 17 with the middle element, 11.
2 4 5 7 10 11 15 20 25 30 35
- Consider the 2nd half since 17 is greater.
2 4 5 7 10 11 15 20 25 30 35
- Compare 17 with the middle element, 25.
15 20 25 30 35
- Consider the 1st half since 17 is smaller.
15 20 25 30 35
- Compare 17 with the middle element, 15.
15 20
- Consider the 2nd half since 17 is greater.
15 20
- Compare 17 with the 20.
20

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Binary Search
Example

Consider the following array: {2,4,5,7,10,11,15,20,25,30,35}


Suppose we want to search for the element 17 in the array.
- Compare 17 with the middle element, 11.
2 4 5 7 10 11 15 20 25 30 35
- Consider the 2nd half since 17 is greater.
2 4 5 7 10 11 15 20 25 30 35
- Compare 17 with the middle element, 25.
15 20 25 30 35
- Consider the 1st half since 17 is smaller.
15 20 25 30 35
- Compare 17 with the middle element, 15.
15 20
- Consider the 2nd half since 17 is greater.
15 20
- Compare 17 with the 20.
20
- 17 is not present.
Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A
Recursion in C

Binary Search
Program

Recursive Implementation of Binary Search


The function binary_search takes the following arguments:
- ar: array, l: start index, u: end index, and elt: element to be searched
If elt is present, returns the index at which elt is present, otherwise returns
-1.

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Binary Search
Program

Recursive Implementation of Binary Search


The function binary_search takes the following arguments:
- ar: array, l: start index, u: end index, and elt: element to be searched
If elt is present, returns the index at which elt is present, otherwise returns
-1.

1 int binary_search(int *ar, int l, int u, int elt){


2 if (l>u) return -1;
3 else{
4 if (ar[(l+u)/2] == elt) return (l+u)/2;
5 else if (ar[(l+u)/2] > elt) return binary_search(ar, l, (l+u)
/2 - 1, elt);
6 else return binary_search(ar, (l+u)/2 + 1, u, elt);
7 }
8 }

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Binary Search
Analysis

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Binary Search
Analysis

Number of function calls: log(n) +1 (in the worst case).

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Binary Search
Analysis

Number of function calls: log(n) +1 (in the worst case).


Time taken: log(n)+1

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Binary Search
Analysis

Number of function calls: log(n) +1 (in the worst case).


Time taken: log(n)+1
Stack Depth: log (n) +1.

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Binary Search
Analysis

Number of function calls: log(n) +1 (in the worst case).


Time taken: log(n)+1
Stack Depth: log (n) +1.
Only works if the array is sorted in ascending or descending
order.

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Announcements

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Announcements

Practice Problems for upcoming Lab Exam on the


Programming Gym
http://www2.cse.iitk.ac.in:81/newonj/contests.php?contestID=17
Time yourself to 4 hours and take the contest.

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Announcements

Practice Problems for upcoming Lab Exam on the


Programming Gym
http://www2.cse.iitk.ac.in:81/newonj/contests.php?contestID=17
Time yourself to 4 hours and take the contest.
Students who scored 40/50 in the previous contest:
- Prawal Gangwar, Amit Kumar, Nishant Rai, Lakshay
Garg, Divyank Aggarwal and Sarthak Garg
- Several students also scored 30 out 50.
- Congratulations to all!

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Announcements

Practice Problems for upcoming Lab Exam on the


Programming Gym
http://www2.cse.iitk.ac.in:81/newonj/contests.php?contestID=17
Time yourself to 4 hours and take the contest.
Students who scored 40/50 in the previous contest:
- Prawal Gangwar, Amit Kumar, Nishant Rai, Lakshay
Garg, Divyank Aggarwal and Sarthak Garg
- Several students also scored 30 out 50.
- Congratulations to all!
Students who got 100/100 in Lab Exam 1:
- Prakhar Kulshreshtha, Satyam Dwivedi and Lakshay Garg
- Congratulations and well done!

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Global Variables

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Global Variables

Variables declared outside every


function definition (after the
#include statements).

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Global Variables

Variables declared outside every


function definition (after the
#include statements).

Can be accessed by all functions


in the program.

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Global Variables

Variables declared outside every


function definition (after the
#include statements).

Can be accessed by all functions


in the program.

1 #include<stdio.h>
2 int g=10, h=20;
3
4 int add(){
5 return g+h;
6 }
7
8 int main(){
9 printf("%d %d %d\n",g,h,add());
10 return 0;
11 }

10 20 30
Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A
Recursion in C

Global Variables

Variables declared outside every


function definition (after the
#include statements).

Can be accessed by all functions


in the program.

1 #include<stdio.h>
2 int g=10, h=20;
3
4 int add(){
5 return g+h;
6 }
7
8 int main(){
9 printf("%d %d %d\n",g,h,add());
10 return 0;
11 }

Output: 10 20 30
Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A
Recursion in C

Global Variables

What if a variable is declared


Variables declared outside every
inside a function that has the
function definition (after the
same name as a global variable?
#include statements).

Can be accessed by all functions


in the program.

1 #include<stdio.h>
2 int g=10, h=20;
3
4 int add(){
5 return g+h;
6 }
7
8 int main(){
9 printf("%d %d %d\n",g,h,add());
10 return 0;
11 }

Output: 10 20 30
Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A
Recursion in C

Global Variables

What if a variable is declared


Variables declared outside every
inside a function that has the
function definition (after the
same name as a global variable?
#include statements).
The global variable is
Can be accessed by all functions
shadowed inside that
in the program.
particular function only.
1 #include<stdio.h>
2 int g=10, h=20;
3
4 int add(){
5 return g+h;
6 }
7
8 int main(){
9 printf("%d %d %d\n",g,h,add());
10 return 0;
11 }

Output: 10 20 30
Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A
Recursion in C

Global Variables

What if a variable is declared


Variables declared outside every
inside a function that has the
function definition (after the
same name as a global variable?
#include statements).
The global variable is
Can be accessed by all functions
shadowed inside that
in the program.
particular function only.
1 #include<stdio.h>
2 int g=10, h=20; 1 #include<stdio.h>
3 2 int g=10;
4 int add(){ 3 void fun1(){
5 return g+h; 4 int g=20;
6 } 5 printf("%d\n",g);
7 6 } 10
8 int main(){ 7 int main(){ 20
9 printf("%d %d %d\n",g,h,add()); 8 printf("%d\n",g); 10
10 return 0; 9 fun1();
11 } 10 printf("%d\n",g);
11 return 0;
12 }
Output: 10 20 30
Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A
Recursion in C

Global Variables

What if a variable is declared


Variables declared outside every
inside a function that has the
function definition (after the
same name as a global variable?
#include statements).
The global variable is
Can be accessed by all functions
shadowed inside that
in the program.
particular function only.
1 #include<stdio.h>
2 int g=10, h=20; 1 #include<stdio.h>
3 2 int g=10;
4 int add(){ 3 void fun1(){
5 return g+h; 4 int g=20; Output:
6 } 5 printf("%d\n",g);
7 6 } 10
8 int main(){ 7 int main(){ 20
9 printf("%d %d %d\n",g,h,add()); 8 printf("%d\n",g); 10
10 return 0; 9 fun1();
11 } 10 printf("%d\n",g);
11 return 0;
12 }
Output: 10 20 30
Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A
Recursion in C

Counting Function Calls


Example - Fibonacci Numbers

F (n) = F (n 1) + F (n 2) and F (1) = F (2) = 1.

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Counting Function Calls


Example - Fibonacci Numbers

F (n) = F (n 1) + F (n 2) and F (1) = F (2) = 1.


We will use a global variable to count the number of recursive
calls made in computing the n-th Fibonacci number.

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Counting Function Calls


Example - Fibonacci Numbers

F (n) = F (n 1) + F (n 2) and F (1) = F (2) = 1.


We will use a global variable to count the number of recursive
calls made in computing the n-th Fibonacci number.

1 #include<stdio.h>
2 int count = 0;
3
4 int fib(int n){ Output:
5 count = count+1;
6 if (n==1 || n==2) return 1;
7 else return fib(n-1) + fib(n-2);
8 }
9
10 int main(){
11 int num;
12 scanf("%d",&num);
13 printf("%d, %d\n",fib(num),count);
14 return 0;
15 }

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Counting Function Calls


Example - Fibonacci Numbers

F (n) = F (n 1) + F (n 2) and F (1) = F (2) = 1.


We will use a global variable to count the number of recursive
calls made in computing the n-th Fibonacci number.

1 #include<stdio.h>
2 int count = 0;
3
4 int fib(int n){ Output:
5 count = count+1;
6 if (n==1 || n==2) return 1;
Value of num Output
7 else return fib(n-1) + fib(n-2);
8 }
9
10 int main(){
11 int num;
12 scanf("%d",&num);
13 printf("%d, %d\n",fib(num),count);
14 return 0;
15 }

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Counting Function Calls


Example - Fibonacci Numbers

F (n) = F (n 1) + F (n 2) and F (1) = F (2) = 1.


We will use a global variable to count the number of recursive
calls made in computing the n-th Fibonacci number.

1 #include<stdio.h>
2 int count = 0;
3
4 int fib(int n){ Output:
5 count = count+1;
6 if (n==1 || n==2) return 1;
Value of num Output
7 else return fib(n-1) + fib(n-2); 3 2, 3
8 }
9
10 int main(){
11 int num;
12 scanf("%d",&num);
13 printf("%d, %d\n",fib(num),count);
14 return 0;
15 }

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Counting Function Calls


Example - Fibonacci Numbers

F (n) = F (n 1) + F (n 2) and F (1) = F (2) = 1.


We will use a global variable to count the number of recursive
calls made in computing the n-th Fibonacci number.

1 #include<stdio.h>
2 int count = 0;
3
4 int fib(int n){ Output:
5 count = count+1;
6 if (n==1 || n==2) return 1;
Value of num Output
7 else return fib(n-1) + fib(n-2); 3 2, 3
8 }
9 10 55, 109
10 int main(){ 20 6765, 13529
11 int num;
12 scanf("%d",&num); 30 832040, 1664079
13 printf("%d, %d\n",fib(num),count);
14 return 0;
15 }

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Return of the Sorting Problem


Recursive Approach

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Return of the Sorting Problem


Recursive Approach

We have seen the Selection Sort algorithm for sorting an array.

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Return of the Sorting Problem


Recursive Approach

We have seen the Selection Sort algorithm for sorting an array.


Let us try to devise a recursive approach.
Recursive Approach:

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Return of the Sorting Problem


Recursive Approach

We have seen the Selection Sort algorithm for sorting an array.


Let us try to devise a recursive approach.
Recursive Approach:
- Divide the array into two halves.

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Return of the Sorting Problem


Recursive Approach

We have seen the Selection Sort algorithm for sorting an array.


Let us try to devise a recursive approach.
Recursive Approach:
- Divide the array into two halves.
Thats easy!

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Return of the Sorting Problem


Recursive Approach

We have seen the Selection Sort algorithm for sorting an array.


Let us try to devise a recursive approach.
Recursive Approach:
- Divide the array into two halves.
Thats easy!
- Sort them recursively.

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Return of the Sorting Problem


Recursive Approach

We have seen the Selection Sort algorithm for sorting an array.


Let us try to devise a recursive approach.
Recursive Approach:
- Divide the array into two halves.
Thats easy!
- Sort them recursively.
- Merge the two sorted sub arrays.

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Return of the Sorting Problem


Recursive Approach

We have seen the Selection Sort algorithm for sorting an array.


Let us try to devise a recursive approach.
Recursive Approach:
- Divide the array into two halves.
Thats easy!
- Sort them recursively.
- Merge the two sorted sub arrays.
How do we merge two sorted arrays?

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Sorting an Array
Merging Two Sorted Arrays First Approach

Solution Idea:

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Sorting an Array
Merging Two Sorted Arrays First Approach

Solution Idea:
- Let A and B be the two sorted arrays.

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Sorting an Array
Merging Two Sorted Arrays First Approach

Solution Idea:
- Let A and B be the two sorted arrays.
- For every element in array B, check where it would fit in array
A by scanning from left to right.

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Sorting an Array
Merging Two Sorted Arrays First Approach

Solution Idea:
- Let A and B be the two sorted arrays.
- For every element in array B, check where it would fit in array
A by scanning from left to right.
Example: Consider 2 sorted arrays A = {1, 2, 7, 9} and
B = {3, 5, 11}.

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Sorting an Array
Merging Two Sorted Arrays First Approach

Solution Idea:
- Let A and B be the two sorted arrays.
- For every element in array B, check where it would fit in array
A by scanning from left to right.
Example: Consider 2 sorted arrays A = {1, 2, 7, 9} and
B = {3, 5, 11}.
First 3 is inserted: {1, 2, 3, 7, 9}

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Sorting an Array
Merging Two Sorted Arrays First Approach

Solution Idea:
- Let A and B be the two sorted arrays.
- For every element in array B, check where it would fit in array
A by scanning from left to right.
Example: Consider 2 sorted arrays A = {1, 2, 7, 9} and
B = {3, 5, 11}.
First 3 is inserted: {1, 2, 3, 7, 9}
Then 5 is inserted: {1, 2, 3, 5, 7, 9}

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Sorting an Array
Merging Two Sorted Arrays First Approach

Solution Idea:
- Let A and B be the two sorted arrays.
- For every element in array B, check where it would fit in array
A by scanning from left to right.
Example: Consider 2 sorted arrays A = {1, 2, 7, 9} and
B = {3, 5, 11}.
First 3 is inserted: {1, 2, 3, 7, 9}
Then 5 is inserted: {1, 2, 3, 5, 7, 9}
Finally 11 is inserted: {1, 2, 3, 5, 7, 9, 11}

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Sorting an Array
Merging Two Sorted Arrays First Approach

Solution Idea:
- Let A and B be the two sorted arrays.
- For every element in array B, check where it would fit in array
A by scanning from left to right.
Example: Consider 2 sorted arrays A = {1, 2, 7, 9} and
B = {3, 5, 11}.
First 3 is inserted: {1, 2, 3, 7, 9}
Then 5 is inserted: {1, 2, 3, 5, 7, 9}
Finally 11 is inserted: {1, 2, 3, 5, 7, 9, 11}
If A has size n and B has size m, how many steps will this
algorithm take in the worst case

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Sorting an Array
Merging Two Sorted Arrays First Approach

Solution Idea:
- Let A and B be the two sorted arrays.
- For every element in array B, check where it would fit in array
A by scanning from left to right.
Example: Consider 2 sorted arrays A = {1, 2, 7, 9} and
B = {3, 5, 11}.
First 3 is inserted: {1, 2, 3, 7, 9}
Then 5 is inserted: {1, 2, 3, 5, 7, 9}
Finally 11 is inserted: {1, 2, 3, 5, 7, 9, 11}
If A has size n and B has size m, how many steps will this
algorithm take in the worst case
- Number of steps n + n + . . . (m times) = n m. (Verify
yourself!)

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Sorting an Array
Merging Two Sorted Arrays First Approach

Solution Idea:
- Let A and B be the two sorted arrays.
- For every element in array B, check where it would fit in array
A by scanning from left to right.
Example: Consider 2 sorted arrays A = {1, 2, 7, 9} and
B = {3, 5, 11}.
First 3 is inserted: {1, 2, 3, 7, 9}
Then 5 is inserted: {1, 2, 3, 5, 7, 9}
Finally 11 is inserted: {1, 2, 3, 5, 7, 9, 11}
If A has size n and B has size m, how many steps will this
algorithm take in the worst case
- Number of steps n + n + . . . (m times) = n m. (Verify
yourself!)
Now suppose A and B are halves of an array of size n (both
have size n/2).

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Sorting an Array
Merging Two Sorted Arrays First Approach

Solution Idea:
- Let A and B be the two sorted arrays.
- For every element in array B, check where it would fit in array
A by scanning from left to right.
Example: Consider 2 sorted arrays A = {1, 2, 7, 9} and
B = {3, 5, 11}.
First 3 is inserted: {1, 2, 3, 7, 9}
Then 5 is inserted: {1, 2, 3, 5, 7, 9}
Finally 11 is inserted: {1, 2, 3, 5, 7, 9, 11}
If A has size n and B has size m, how many steps will this
algorithm take in the worst case
- Number of steps n + n + . . . (m times) = n m. (Verify
yourself!)
Now suppose A and B are halves of an array of size n (both
have size n/2).
Number of steps = n2 /4.
Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A
Recursion in C

Sorting an Array
Merging Two Sorted Arrays Second Approach (Example)

Let A = {1, 2, 7, 9} and B = {3, 8, 11, 14} be two sorted arrays.


A 1 2 7 9 B 3 8 11 14 C

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Sorting an Array
Merging Two Sorted Arrays Second Approach (Example)

Let A = {1, 2, 7, 9} and B = {3, 8, 11, 14} be two sorted arrays.


A 1 2 7 9 B 3 8 11 14 C

A 1 2 7 9 B 3 8 11 14 C 1

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Sorting an Array
Merging Two Sorted Arrays Second Approach (Example)

Let A = {1, 2, 7, 9} and B = {3, 8, 11, 14} be two sorted arrays.


A 1 2 7 9 B 3 8 11 14 C

A 1 2 7 9 B 3 8 11 14 C 1

A 1 2 7 9 B 3 8 11 14 C 1 2

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Sorting an Array
Merging Two Sorted Arrays Second Approach (Example)

Let A = {1, 2, 7, 9} and B = {3, 8, 11, 14} be two sorted arrays.


A 1 2 7 9 B 3 8 11 14 C

A 1 2 7 9 B 3 8 11 14 C 1

A 1 2 7 9 B 3 8 11 14 C 1 2

A 1 2 7 9 B 3 8 11 14 C 1 2 3

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Sorting an Array
Merging Two Sorted Arrays Second Approach (Example)

Let A = {1, 2, 7, 9} and B = {3, 8, 11, 14} be two sorted arrays.


A 1 2 7 9 B 3 8 11 14 C

A 1 2 7 9 B 3 8 11 14 C 1

A 1 2 7 9 B 3 8 11 14 C 1 2

A 1 2 7 9 B 3 8 11 14 C 1 2 3

A 1 2 7 9 B 3 8 11 14 C 1 2 3 7

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Sorting an Array
Merging Two Sorted Arrays Second Approach (Example)

Let A = {1, 2, 7, 9} and B = {3, 8, 11, 14} be two sorted arrays.


A 1 2 7 9 B 3 8 11 14 C

A 1 2 7 9 B 3 8 11 14 C 1

A 1 2 7 9 B 3 8 11 14 C 1 2

A 1 2 7 9 B 3 8 11 14 C 1 2 3

A 1 2 7 9 B 3 8 11 14 C 1 2 3 7

A 1 2 7 9 B 3 8 11 14 C 1 2 3 7 8

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Sorting an Array
Merging Two Sorted Arrays Second Approach (Example)

Let A = {1, 2, 7, 9} and B = {3, 8, 11, 14} be two sorted arrays.


A 1 2 7 9 B 3 8 11 14 C

A 1 2 7 9 B 3 8 11 14 C 1

A 1 2 7 9 B 3 8 11 14 C 1 2

A 1 2 7 9 B 3 8 11 14 C 1 2 3

A 1 2 7 9 B 3 8 11 14 C 1 2 3 7

A 1 2 7 9 B 3 8 11 14 C 1 2 3 7 8

A 1 2 7 9 B 3 8 11 14 C 1 2 3 7 8 9

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Sorting an Array
Merging Two Sorted Arrays Second Approach (Example)

Let A = {1, 2, 7, 9} and B = {3, 8, 11, 14} be two sorted arrays.


A 1 2 7 9 B 3 8 11 14 C

A 1 2 7 9 B 3 8 11 14 C 1

A 1 2 7 9 B 3 8 11 14 C 1 2

A 1 2 7 9 B 3 8 11 14 C 1 2 3

A 1 2 7 9 B 3 8 11 14 C 1 2 3 7

A 1 2 7 9 B 3 8 11 14 C 1 2 3 7 8

A 1 2 7 9 B 3 8 11 14 C 1 2 3 7 8 9

A 1 2 7 9 B 3 8 11 14 C 1 2 3 7 8 9 11

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Sorting an Array
Merging Two Sorted Arrays Second Approach (Example)

Let A = {1, 2, 7, 9} and B = {3, 8, 11, 14} be two sorted arrays.


A 1 2 7 9 B 3 8 11 14 C

A 1 2 7 9 B 3 8 11 14 C 1

A 1 2 7 9 B 3 8 11 14 C 1 2

A 1 2 7 9 B 3 8 11 14 C 1 2 3

A 1 2 7 9 B 3 8 11 14 C 1 2 3 7

A 1 2 7 9 B 3 8 11 14 C 1 2 3 7 8

A 1 2 7 9 B 3 8 11 14 C 1 2 3 7 8 9

A 1 2 7 9 B 3 8 11 14 C 1 2 3 7 8 9 11

A 1 2 7 9 B 3 8 11 14 C 1 2 3 7 8 9 11 14

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Sorting an Array
Merging Two Sorted Arrays Second Approach (Algorithm)

1 Input: Array A of size n and array B of size m.

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Sorting an Array
Merging Two Sorted Arrays Second Approach (Algorithm)

1 Input: Array A of size n and array B of size m.


2 Create an empty array C of size n + m.

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Sorting an Array
Merging Two Sorted Arrays Second Approach (Algorithm)

1 Input: Array A of size n and array B of size m.


2 Create an empty array C of size n + m.
3 Variables i, j and k are the array variables for the arrays A, B
and C respectively

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Sorting an Array
Merging Two Sorted Arrays Second Approach (Algorithm)

1 Input: Array A of size n and array B of size m.


2 Create an empty array C of size n + m.
3 Variables i, j and k are the array variables for the arrays A, B
and C respectively
4 At each iteration, compare the i-th element of A (say u) with
the j-th element of B (say v )

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Sorting an Array
Merging Two Sorted Arrays Second Approach (Algorithm)

1 Input: Array A of size n and array B of size m.


2 Create an empty array C of size n + m.
3 Variables i, j and k are the array variables for the arrays A, B
and C respectively
4 At each iteration, compare the i-th element of A (say u) with
the j-th element of B (say v )
- if u is smaller, copy u to C; increment i and k,

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Sorting an Array
Merging Two Sorted Arrays Second Approach (Algorithm)

1 Input: Array A of size n and array B of size m.


2 Create an empty array C of size n + m.
3 Variables i, j and k are the array variables for the arrays A, B
and C respectively
4 At each iteration, compare the i-th element of A (say u) with
the j-th element of B (say v )
- if u is smaller, copy u to C; increment i and k,
- otherwise, copy v to C; increment j and k,

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Sorting an Array
Merging Two Sorted Arrays Second Approach (Algorithm)

1 Input: Array A of size n and array B of size m.


2 Create an empty array C of size n + m.
3 Variables i, j and k are the array variables for the arrays A, B
and C respectively
4 At each iteration, compare the i-th element of A (say u) with
the j-th element of B (say v )
- if u is smaller, copy u to C; increment i and k,
- otherwise, copy v to C; increment j and k,
Number of steps 3(n + m).
- The constant 3 is not very important as it does not vary with
different sized arrays.

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Sorting an Array
Merging Two Sorted Arrays Second Approach (Algorithm)

1 Input: Array A of size n and array B of size m.


2 Create an empty array C of size n + m.
3 Variables i, j and k are the array variables for the arrays A, B
and C respectively
4 At each iteration, compare the i-th element of A (say u) with
the j-th element of B (say v )
- if u is smaller, copy u to C; increment i and k,
- otherwise, copy v to C; increment j and k,
Number of steps 3(n + m).
- The constant 3 is not very important as it does not vary with
different sized arrays.
Now suppose A and B are halves of an array of size n (both
have size n/2).

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Sorting an Array
Merging Two Sorted Arrays Second Approach (Algorithm)

1 Input: Array A of size n and array B of size m.


2 Create an empty array C of size n + m.
3 Variables i, j and k are the array variables for the arrays A, B
and C respectively
4 At each iteration, compare the i-th element of A (say u) with
the j-th element of B (say v )
- if u is smaller, copy u to C; increment i and k,
- otherwise, copy v to C; increment j and k,
Number of steps 3(n + m).
- The constant 3 is not very important as it does not vary with
different sized arrays.
Now suppose A and B are halves of an array of size n (both
have size n/2).
Number of steps = 3n.

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Sorting an Array
Merging Two Sorted Arrays Second Approach (Algorithm)

1 Input: Array A of size n and array B of size m.


2 Create an empty array C of size n + m.
3 Variables i, j and k are the array variables for the arrays A, B
and C respectively
4 At each iteration, compare the i-th element of A (say u) with
the j-th element of B (say v )
- if u is smaller, copy u to C; increment i and k,
- otherwise, copy v to C; increment j and k,
Number of steps 3(n + m).
- The constant 3 is not very important as it does not vary with
different sized arrays.
Now suppose A and B are halves of an array of size n (both
have size n/2).
Number of steps = 3n.
Much smaller than n2 /4 for large values of n.
Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A
Recursion in C

Sorting an Array
Merge Sort Complete Algorithm

MergeSort(A[0, . . . , n 1], n)

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Sorting an Array
Merge Sort Complete Algorithm

MergeSort(A[0, . . . , n 1], n)
1 If n > 1,
1 MergeSort(A[0, . . . , n/2 1], n/2)
2 MergeSort(A[n/2, . . . , n 1], n n/2)

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Sorting an Array
Merge Sort Complete Algorithm

MergeSort(A[0, . . . , n 1], n)
1 If n > 1,
1 MergeSort(A[0, . . . , n/2 1], n/2)
2 MergeSort(A[n/2, . . . , n 1], n n/2)
3 Merge(A, n)

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Sorting an Array
Merge Sort Complete Algorithm

MergeSort(A[0, . . . , n 1], n)
1 If n > 1,
1 MergeSort(A[0, . . . , n/2 1], n/2)
2 MergeSort(A[n/2, . . . , n 1], n n/2)
3 Merge(A, n)
Description of the functions
MergeSort: Takes an array A of size n and sorts it

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Sorting an Array
Merge Sort Complete Algorithm

MergeSort(A[0, . . . , n 1], n)
1 If n > 1,
1 MergeSort(A[0, . . . , n/2 1], n/2)
2 MergeSort(A[n/2, . . . , n 1], n n/2)
3 Merge(A, n)
Description of the functions
MergeSort: Takes an array A of size n and sorts it
Merge: Takes an array A of size n with the assumption that
the first n/2 elements and the remaining n n/2 elements are
sorted. Merges the two arrays and puts it back in A.

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Sorting an Array
Merge Sort C Code
1 void merge(int *ar, int n){
2 int *temp, i, j=0, k=n/2;
3 temp = (int *)malloc(sizeof(int)*n);
4 for(i=0; i<n; i++){
5 if ((j < n/2) && (k < n)){
6 if (ar[j] < ar[k]){
7 temp[i] = ar[j];
8 j++; }
9 else{
10 temp[i] = ar[k];
11 k++; }
12 }
13 else if (j == n/2){
14 temp[i] = ar[k];
15 k++; }
16 else{
17 temp[i] = ar[j];
18 j++; }
19 }
20 for (i=0; i<n; i++)
21 ar[i] = temp[i];
22 free(temp);}
Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A
Recursion in C

Sorting an Array
Merge Sort C Code
1 void merge(int *ar, int n){
2 int *temp, i, j=0, k=n/2;
3 temp = (int *)malloc(sizeof(int)*n);
4 for(i=0; i<n; i++){ 1 void merge_sort(int *ar, int n){
5 if ((j < n/2) && (k < n)){ 2 if (n>1){
6 if (ar[j] < ar[k]){ 3 merge_sort(ar,n/2);
7 temp[i] = ar[j]; 4 merge_sort(ar+(n/2), n-(n/2));
8 j++; } 5 merge(ar,n);
9 else{ 6 }
10 temp[i] = ar[k]; 7 }
11 k++; } 8
12 } 9 int main(){
13 else if (j == n/2){ 10 int ar1[]={2,5,4,8,6,9,8,6,1,4,7};
14 temp[i] = ar[k]; 11 merge_sort(ar1,11);
15 k++; } 12 display(ar1,11); //displaying array
16 else{ 13 return 0;
17 temp[i] = ar[j]; 14 }
18 j++; }
19 }
20 for (i=0; i<n; i++) 1 2 4 4 5 6 6 7 8 8 9
21 ar[i] = temp[i];
22 free(temp);}
Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A
Recursion in C

Sorting an Array
Merge Sort C Code
1 void merge(int *ar, int n){
2 int *temp, i, j=0, k=n/2;
3 temp = (int *)malloc(sizeof(int)*n);
4 for(i=0; i<n; i++){ 1 void merge_sort(int *ar, int n){
5 if ((j < n/2) && (k < n)){ 2 if (n>1){
6 if (ar[j] < ar[k]){ 3 merge_sort(ar,n/2);
7 temp[i] = ar[j]; 4 merge_sort(ar+(n/2), n-(n/2));
8 j++; } 5 merge(ar,n);
9 else{ 6 }
10 temp[i] = ar[k]; 7 }
11 k++; } 8
12 } 9 int main(){
13 else if (j == n/2){ 10 int ar1[]={2,5,4,8,6,9,8,6,1,4,7};
14 temp[i] = ar[k]; 11 merge_sort(ar1,11);
15 k++; } 12 display(ar1,11); //displaying array
16 else{ 13 return 0;
17 temp[i] = ar[j]; 14 }
18 j++; }
19 }
20 for (i=0; i<n; i++) Output: 1 2 4 4 5 6 6 7 8 8 9
21 ar[i] = temp[i];
22 free(temp);}
Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A
Recursion in C

Sorting an Array
Merge Sort Time Analysis (the best part)

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Sorting an Array
Merge Sort Time Analysis (the best part)

For the sake of simplicity lets assume n = 2k for some k. (In


general, n need not be a power of 2, but the analysis does not
change much.)

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Sorting an Array
Merge Sort Time Analysis (the best part)

For the sake of simplicity lets assume n = 2k for some k. (In


general, n need not be a power of 2, but the analysis does not
change much.)
Function Call Tree

n=8

4 4

2 2 2 2

1 1 1 1 1 1 1 1

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Sorting an Array
Merge Sort Time Analysis (the best part)

For the sake of simplicity lets assume n = 2k for some k. (In


general, n need not be a power of 2, but the analysis does not
change much.)
Function Call Tree
Let T (n) be the time taken by
MergeSort on an array of size n. Then,

n=8

4 4

2 2 2 2

1 1 1 1 1 1 1 1

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Sorting an Array
Merge Sort Time Analysis (the best part)

For the sake of simplicity lets assume n = 2k for some k. (In


general, n need not be a power of 2, but the analysis does not
change much.)
Function Call Tree
Let T (n) be the time taken by
MergeSort on an array of size n. Then,
T (n) = 2T (n/2) + 4n

n=8

4 4

2 2 2 2

1 1 1 1 1 1 1 1

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Sorting an Array
Merge Sort Time Analysis (the best part)

For the sake of simplicity lets assume n = 2k for some k. (In


general, n need not be a power of 2, but the analysis does not
change much.)
Function Call Tree
Let T (n) be the time taken by
MergeSort on an array of size n. Then,
T (n) = 2T (n/2) + 4n
= 2(2T (n/4) + 4(n/2)) + 4n
n=8

4 4

2 2 2 2

1 1 1 1 1 1 1 1

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Sorting an Array
Merge Sort Time Analysis (the best part)

For the sake of simplicity lets assume n = 2k for some k. (In


general, n need not be a power of 2, but the analysis does not
change much.)
Function Call Tree
Let T (n) be the time taken by
MergeSort on an array of size n. Then,
T (n) = 2T (n/2) + 4n
= 2(2T (n/4) + 4(n/2)) + 4n
n=8
= 22 T (n/4) + 8n

4 4

2 2 2 2

1 1 1 1 1 1 1 1

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Sorting an Array
Merge Sort Time Analysis (the best part)

For the sake of simplicity lets assume n = 2k for some k. (In


general, n need not be a power of 2, but the analysis does not
change much.)
Function Call Tree
Let T (n) be the time taken by
MergeSort on an array of size n. Then,
T (n) = 2T (n/2) + 4n
= 2(2T (n/4) + 4(n/2)) + 4n
n=8
= 22 T (n/4) + 8n
= 22 (2T (n/8) + 4(n/4)) + 8n
4 4

2 2 2 2

1 1 1 1 1 1 1 1

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Sorting an Array
Merge Sort Time Analysis (the best part)

For the sake of simplicity lets assume n = 2k for some k. (In


general, n need not be a power of 2, but the analysis does not
change much.)
Function Call Tree
Let T (n) be the time taken by
MergeSort on an array of size n. Then,
T (n) = 2T (n/2) + 4n
= 2(2T (n/4) + 4(n/2)) + 4n
n=8
= 22 T (n/4) + 8n
= 22 (2T (n/8) + 4(n/4)) + 8n
4 4
= 23 T (n/8) + 12n
2 2 2 2

1 1 1 1 1 1 1 1

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Sorting an Array
Merge Sort Time Analysis (the best part)

For the sake of simplicity lets assume n = 2k for some k. (In


general, n need not be a power of 2, but the analysis does not
change much.)
Function Call Tree
Let T (n) be the time taken by
MergeSort on an array of size n. Then,
T (n) = 2T (n/2) + 4n
= 2(2T (n/4) + 4(n/2)) + 4n
n=8
= 22 T (n/4) + 8n
= 22 (2T (n/8) + 4(n/4)) + 8n
4 4
= 23 T (n/8) + 12n
2 2 2 2
= 2k T (n/2k ) + k 4n
1 1 1 1 1 1 1 1

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Sorting an Array
Merge Sort Time Analysis (the best part)

For the sake of simplicity lets assume n = 2k for some k. (In


general, n need not be a power of 2, but the analysis does not
change much.)
Function Call Tree
Let T (n) be the time taken by
MergeSort on an array of size n. Then,
T (n) = 2T (n/2) + 4n
= 2(2T (n/4) + 4(n/2)) + 4n
n=8
= 22 T (n/4) + 8n
= 22 (2T (n/8) + 4(n/4)) + 8n
4 4
= 23 T (n/8) + 12n
2 2 2 2
= 2k T (n/2k ) + k 4n
1 1 1 1 1 1 1 1 = n T (1) + log2 n 4n

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Sorting an Array
Merge Sort Time Analysis (the best part)

For the sake of simplicity lets assume n = 2k for some k. (In


general, n need not be a power of 2, but the analysis does not
change much.)
Function Call Tree
Let T (n) be the time taken by
MergeSort on an array of size n. Then,
T (n) = 2T (n/2) + 4n
= 2(2T (n/4) + 4(n/2)) + 4n
n=8
= 22 T (n/4) + 8n
= 22 (2T (n/8) + 4(n/4)) + 8n
4 4
= 23 T (n/8) + 12n
2 2 2 2
= 2k T (n/2k ) + k 4n
1 1 1 1 1 1 1 1 = n T (1) + log2 n 4n
5n log2 n

Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A


Recursion in C

Sorting an Array
Merge Sort Time Analysis (the best part)

For the sake of simplicity lets assume n = 2k for some k. (In


general, n need not be a power of 2, but the analysis does not
change much.)
Function Call Tree
Let T (n) be the time taken by
MergeSort on an array of size n. Then,
T (n) = 2T (n/2) + 4n
= 2(2T (n/4) + 4(n/2)) + 4n
n=8
= 22 T (n/4) + 8n
= 22 (2T (n/8) + 4(n/4)) + 8n
4 4
= 23 T (n/8) + 12n
2 2 2 2
= 2k T (n/2k ) + k 4n
1 1 1 1 1 1 1 1 = n T (1) + log2 n 4n
5n log2 n
Recall that time take by selection sort was n(n 1)/2.
Raghunath Tewari rtewari@cse.iitk.ac.in ESc101A

Anda mungkin juga menyukai