0% found this document useful (0 votes)
14 views26 pages

LeC-17-Divide and Conquer - Recursion

RECURSION

Uploaded by

laholol309
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views26 pages

LeC-17-Divide and Conquer - Recursion

RECURSION

Uploaded by

laholol309
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 26

Computer

Programming
CS F111
BITS Pilani `
Dubai Campus
BITS Pilani
Dubai Campus

Divide and Conquer – Design using


Recursion
Divide and Conquer- Introduction
Divide and Conquer is a recursive problem-solving approach.
It breaks a problem into subproblems that are similar to
the original problem.
Recursively solves the subproblems.
And finally combines the solutions to the subproblems to solve the
original problem.

Phases of Divide and Conquer


It consists of three phases:
Divide: Dividing the problem into two or more than two sub-
problems that are similar to the original problem but smaller in
size.
Conquer: Solve the sub-problems recursively.
Combine: Combine these solutions to subproblems to create a
solution to the original problem.
BITS Pilani, Dubai Campus
Divide and Conquer- Introduction

BITS Pilani, Dubai Campus


Divide and Conquer- Need
Basic Idea of Divide and Conquer:
• If the problem is easy, solve it directly
• If the problem is difficult to solved as it is, decompose it into
smaller parts. Solve the smaller parts.
• Combine the solutions of simpler parts to form a solution to
the complex problem.

This method usually allows us to reduce the time complexity to


a large extent.

BITS Pilani, Dubai Campus


Divide and Conquer- Need

Normal approach

Normal approach

DAC approach

DAC approach

BITS Pilani, Dubai Campus


Divide and Conquer- Examples
The following are some standard algorithms that follows Divide and
Conquer algorithm.

 Binary Search is a searching algorithm. In each step, the algorithm


compares the input element x with the value of the middle element in
array. If the values match, return the index of the middle. Otherwise, if x
is less than the middle element, then the algorithm recurs for left side of
middle element, else recurs for the right side of the middle element.

 Quicksort is a sorting algorithm. The algorithm picks a pivot element,


rearranges the array elements in such a way that all elements smaller
than the picked pivot element move to left side of pivot, and all greater
elements move to right side. Finally, the algorithm recursively sorts the
subarrays on left and right of pivot element.

 Merge Sort is also a sorting algorithm. The algorithm divides the array
in two halves, recursively sorts them and finally merges the two sorted
halves.
BITS Pilani, Dubai Campus
Divide and Conquer- Examples
 Strassen’s Algorithm is an efficient algorithm to multiply two matrices.
A simple method to multiply two matrices need 3 nested loops and is
O(n^3). Strassen’s algorithm multiplies two matrices in O(n^2.8974)
time.

 Cooley–Tukey Fast Fourier Transform (FFT) algorithm is the most


common algorithm for FFT. It is a divide and conquer algorithm which
works in O(nlogn) time.

 Karatsuba algorithm for fast multiplication it does multiplication of two


n-digit numbers in at most 3 n^{\log_23}\approx 3 n^{1.585}single-digit
multiplications in general (and exactly n^{\log_23} when n is a power of
2). It is therefore faster than the classical algorithm, which requires n2
single-digit products. If n = 210 = 1024, in particular, the exact counts
are 310 = 59, 049 and (210)2 = 1, 048, 576, respectively.

 And many more….

BITS Pilani, Dubai Campus


Recursion- Introduction
Recursion is the process which comes into existence when a function calls
a copy of itself to work on a smaller problem.
Any function which calls itself is called recursive function, and such function
calls are called recursive calls.
In programming languages, if a program allows you to call a function inside
the same function, then it is called a recursive call of the function.
Eg.

BITS Pilani, Dubai Campus


Recursion- base case
The C programming language supports recursion, i.e., a function to call
itself. But while using recursion, programmers need to be careful to define
an exit/ termination condition from the function, otherwise it will go into an
infinite loop.

A recursive function performs the tasks by dividing it into the subtasks.


There is a termination condition defined in the function which is satisfied by
some specific subtask. After this, the recursion stops and the final result is
returned from the function.

The case at which the function doesn't recur is called the base case
whereas the instances where the function keeps calling itself to perform a
subtask, is called the recursive case.

BITS Pilani, Dubai Campus


Recursion- Quick Example
void count_to_ten ( int count )
{
/* we only keep counting if we have a value less than ten
if ( count < 10 )
{
count_to_ten( count + 1 );
}
}
int main()
{
count_to_ten ( 0 );
}

This program ends when we've counted to ten, or more precisely, when
count is no longer less than ten. This is a good base case because it means
that if we have an input greater than ten, we'll stop immediately.
BITS Pilani, Dubai Campus
Eg. 1 Recursion- Sum of n natural numbers
#include <stdio.h> int sum(int n)
int sum(int n); {
if (n != 0)
int main() // sum() function calls itself
{ return n + sum(n-1);
int number, result;
else
printf("Enter a positive integer: "); return n;
scanf("%d", &number); }

result = sum(number); Output:


Enter a positive integer:3
printf("sum = %d", result); sum = 6
return 0;
}

BITS Pilani, Dubai Campus


Eg. 1 Recursion- Sum of n natural numbers contd.

BITS Pilani, Dubai Campus


Eg. 2 Recursion- Factorial of a number
#include <stdio.h> int fact(int n)
{
int fact (int); if (n==0)
return 1;
int main()
{ else if ( n == 1)
int n,f; return 1;

printf("Enter a number : "); else


scanf("%d",&n); return n*fact(n-1);
}
f = fact(n);
Output:
printf("factorial = %d",f); Enter a number: 5
} Factorial = 120

BITS Pilani, Dubai Campus


Eg. 2 Recursion- Factorial of a number contd.

BITS Pilani, Dubai Campus


Eg. 3 Recursion- Find nth term of Fibonacci Series
#include<stdio.h> int fibonacci (int n)
{
int fibonacci(int); if (n==0)
return 0;
void main () else if (n == 1)
{ return 1;
int n,f; else
return fibonacci(n-1)+fibonacci(n-2);
printf("Enter the value of n: "); }
scanf("%d",&n);
Output:
f = fibonacci(n); Enter a value of n: 12
144
printf("%d",f);
} Reference:

BITS Pilani, Dubai Campus


Eg. 4 Recursion- Fibonacci Series
#include <stdio.h> int fibonacci(int i)
int fibonacci(int i); {
if(i == 0)
int main() { {
return 0;
int i; }
if(i == 1)
for (i = 0; i < 10; i++) { {
printf("%d\t\n", fibonacci(i)); return 1;
} }
return fibonacci(i-1) + fibonacci(i-2);
return 0; }
}
Output:
0
1
1
2
3
5
8
13
21
34

BITS Pilani, Dubai Campus


Eg. 5 Recursion- Power of a number
#include <stdio.h> int power(int base, int a)
int power(int n1, int n2); {
if (a != 0)
int main() return (base * power(base, a - 1));
{
int base, a, result; else
return 1;
printf("Enter base number: "); }
scanf("%d", &base);
Output:
printf("Enter power: "); Enter base number: 3
scanf("%d", &a); Enter power number(positive integer): 4
3^4 = 81
result = power(base, a);
printf("%d^%d = %d", base, a, result);
return 0;
}

BITS Pilani, Dubai Campus


Eg. 6 Recursion- Binary Search
1. We basically ignore half of the elements just
after one comparison.

2. Compare x with the middle element.


3. If x matches with middle element, we return
the mid index.
4. Else If x is smaller than the mid element, then
x can only lie in left half subarray after the mid
element. So we recur for left half.
5. Else (x is greater) recur for the right half.

BITS Pilani, Dubai Campus


Eg. 6 Recursion- Binary Search
#include<stdio.h> Output:
int RecursiveBsearch(int A[], int start, int end, int
element) { 55 is found at index 8
if(start>end) return -1;
int mid = (start+end)/2;
if( A[mid] == element ) return mid;
else if( element < A[mid] )
RecursiveBsearch(A, start, mid-1, element);
else
RecursiveBsearch(A, mid+1, end, element);
}
int main() {
int A[] = {0,2,6,11,12,18,34,45,55,99};
int n=55;
printf("%d is found at Index %d \
n",n,RecursiveBsearch(A,0,9,n));
return 0;}
BITS Pilani, Dubai Campus
Overview of Merge Sort

BITS Pilani, Dubai Campus


Overview of Quick Sort

BITS Pilani, Dubai Campus


Recursion v/s Iteration
What are the disadvantages of recursive programming over iterative
programming?
Note that both recursive and iterative programs have the same problem-
solving powers, i.e., every recursive program can be written iteratively and
vice versa is also true. The recursive program has greater space
requirements than iterative program as all functions will remain in the stack
until the base case is reached. It also has greater time requirements
because of function calls and returns overhead.

What are the advantages of recursive programming over iterative


programming?
Recursion provides a clean and simple way to write code. Some problems
are inherently recursive like tree traversals, Tower of Hanoi, etc. For such
problems, it is preferred to write recursive code. We can write such codes
also iteratively with the help of a stack data structure. For example refer
Inorder Tree Traversal without Recursion, Iterative Tower of Hanoi.

BITS Pilani, Dubai Campus


Recursion v/s Iteration
Parameter Recursion Iteration
Definition Recursion involves a recursive Iteration involves the usage of
function which calls itself loops through which a set of
repeatedly until a base statements are executed
condition is not reached. repeatedly until the condition is not
false.
Termination Here termination condition is Termination condition is the
Condition a base case defined within the condition specified in the definition
recursive function. of the loop
Infinite Case If base case is never reached it If condition is never false, it leads
leads to infinite recursion to infinite iteration with computers
leading to memory crash. CPU cycle being used repeatedly.
Memory Recursion uses stack area to Iteration uses the permanent
Usage store the current state of the storage area only for the variables
function, due to which involved in its code block, hence
memory usage is high. memory usage is less.
Code Size Code size is comparatively Code size is comparatively larger.
smaller.

BITS Pilani, Dubai Campus


Recursion v/s Iteration
Parameter Recursion Iteration
Performance Since stack are is used to store Since iteration does not have to keep
and restore the state of re-initializing its component variables
recursive function after every and neither has to store function
function call , performance is states, the performance is fast.
comparatively slow.

Memory There is a possibility of running There is no possibility of running out


Runout out of memory, since for each of memory as stack area is not used.
function call stack area gets
used.
Overhead Recursive functions involve There is no overhead in Iteration.
extensive overhead, as for each
function call the current state,
parameters etc. have to be
pushed and popped out from
stack.

Applications Factorial , Fibonacci Series etc. Finding average of a data series,


creating multiplication table etc.

BITS Pilani, Dubai Campus


Recursion v/s Iteration
Parameter Recursion Iteration
Example #include <stdio.h> #include <stdio.h>
int fact(int n) int main()
{ {
if(n == 0) int i, n = 5, fact = 1;
return 1;
else for(i = 1; i <= n; ++i)
return n * factorial(n-1); fact = fact * i;
}
printf(“Factorial for 5 is %d”, fact);
int main() return 0;
{ }
printf(“Factorial for 5 is %d”, fact(5));
return 0;
}

Output: Factorial for 5 is 120 Output: Factorial for 5 is 120

BITS Pilani, Dubai Campus

You might also like