Professional Documents
Culture Documents
Divide and Conquer and Binary Search
Divide and Conquer and Binary Search
Unit I: Syllabus
• Introduction:
– Algorithm definition
– Algorithm Specification
• Performance Analysis-
– Space complexity
– Time complexity
Learn DAA: From B K Sharma
Unit I: Syllabus
• Randomized Algorithms.
• Divide and conquer- General method
– Applications:
• Binary search
• Merge sort Quick sort
• Strassen’s Matrix Multiplication.
Learn DAA: From B K Sharma
Different Algorithm Design Techniques
Problem
Divide
Sub-problem Sub-problem
Combine
Solution to Problem
Learn DAA: From B K Sharma
Divide and Conquer:- General Method
Algorithm GENDCM(P)
{
if SMALL (P) then
return S(P);
else
{
divide P into smaller instances p1, p2, …. Pk, k≥ 1;
apply GENDCM to each of these sub problems;
return (COMBINE (GENDCM (p1) ,
GENDCM(p2),…., GENDCM (pk));
}
}
Learn DAA: From B K Sharma
Divide and Conquer:- General Method
SMALL (P) is a Boolean valued function which
determines whether the input size is small enough so
that the answer can be computed without splitting.
long fact(long n) 0
{ 1
2
if (n==0)
3
return 1;
else
return n * fact(n-1);
}
Learn DAA: From B K Sharma
Divide and Conquer
Recursive Definition of Factorial Function
=24 6 2
(1) 4!=4 x 3! 1
(2) 3!= 3 x 2!
(3) 2!= 2 x 1! 1
(4) 1!=1 x 0!
(5) 0!=1
Learn DAA: From B K Sharma
Divide and Conquer
Recursive Definition of Factorial Function
=24
n=4 fact(4)=4 * fact(3)
3
6 6
n=3 fact(3)=3 * fact(2)
2
2 2
n=2 fact(2)=2 * fact(1)
1
1 1
n=1 fact(1)=1 * fact(0)
0
1 n=0 1
Learn DAA: From B K Sharma
Divide and Conquer
Recursive Definition of Fibonacci Number
if n = 0 or n = 1, then fibn=n
else if n > 1, then fibn=fibn - 2 + fibn - 1
int Fib(int n)
{
if(n==0) Base Condition
return 0;
else if ( n==1) Base Condition
return 1;
else
return Fib( n-2) + Fib(n-1);
}
Learn DAA: From B K Sharma
Divide and Conquer
Recursive Definition of Fibonacci Number
fib(4) =3
n=4
fib(3) n=3
+ n=2 fib(2)
=2 =1
fib(2) n=2
+ n=1 n=1 + n=0
=1
fib(1) fib(1) fib(0)
=1
n=1 + n=0
=1 =0
fib(1) fib(0)
=1 =0
Learn DAA: From B K Sharma
mid
Found on first step, 45 equals the middle item
Search for 27
1 2 3 4 5 6 7 8 9 10 11
12 15 21 23 27 45 76 77 90 95 98
mid
Search for 27
1 2 3 4 5 6 7 8 9 10 11
12 15 21 23 27 45 76 77 90 95 98
mid
DAA: B K Sharma
mid
Found !
Search for 91
1 2 3 4 5 6 7 8 9 10 11
12 15 21 23 27 45 76 77 90 95 98
91 < 95
Search Completed, No value found mid
DAA: B K Sharma
Binary Search
1 for n 1
T ( n) =
T(n/2) + 1 otherwise
Learn DAA : From B K Sharma
for solving
running time of
if
T(n) has the form
Where,
a ≥ 1 & b > 1
n is the size of the problem.
if
= if
if
Learn DAA : From B K Sharma
Here,
a=1, b=2, f(n)=1
Now,
Find nlogba
nlogba= nlog21= n0= 1
Since,
f(n)=nlogba=1
Master Method’s Case 2 Applies:
T(n) = Θ(nlogba lg n) = Θ(f(n) lg n)= Θ(lgn)
Learn DAA : From B K Sharma
END