You are on page 1of 10

Divide and conquer

University Institute of Engineering (UIE)


Divide and Conquer(DandC)

Dand C is a top-down technique for


designing algorithms .
Breaking or divide:-the problem into
several sub-problems that are similar to
the original problem but smaller in size.
Conquer: -Recursively solving these
sub problems.
Combine: -These solutions to sub
problems to create a solution to the
original problem.
University Institute of Engineering (UIE)
Algorithm

Algorithm DandC (P)


{
If Small(P) then return S(P);
else
{
Divide P into smaller instance p1,p2..pk ,k>1;
Apply DandC to each of these sub problem;
return Combine(DandC(P1),(DandC(P2),..DandC(Pk));
}
}

University Institute of Engineering (UIE)


Recursive Binary Search
Algorithm BinSrch (a,i,l,x)
{
If(l=i) then
{ if(x=a[i]) then return i;
else return 0;
}

else
{ mid:= (i+l)/2;
if (x=a[mid]) then return mid;
else if (x<a[mid]) then
return BinSrch(a,i,mid-1,x);
else return BinSrch(a,mid+1,l,x);
}
}
University Institute of Engineering (UIE)
Iterative Binary Search
Algorithm BinSearch(a,n,x)
{
low:=1;high:=n;
while(low<high) do
{
mid:=(low+high)/2;
if(x<a[mid]) then high:=mid-1;
else if (x>a[mid]) then low:=mid+1;
else return mid;
}
return 0;
}
University Institute of Engineering (UIE)
Example
Let us select the 14 entries

-15,-6,0,7,9,23,54,82,101,112,125,131,142,151

Place them in [a:14].


Find x=151
low high mid
1 14 7
8 14 11
12 14 13
14 14 14
found
University Institute of Engineering (UIE)
Example
Let us select the 14 entries

-15,-6,0,7,9,23,54,82,101,112,125,131,142,151

Place them in [a:14].


Find x=-14
low high mid
1 14 7
1 6 3
1 2 1
2 2 2
2 1 not found

University Institute of Engineering (UIE)


Example
Let us select the 14 entries

-15,-6,0,7,9,23,54,82,101,112,125,131,142,151

Place them in [a:14].


Find x=9
low high mid
1 14 7
1 6 3
4 6 5
found
Successful search unsuccessful search
(1), (log n), (log n) (log n)
Best, average, worst Best, average, worst

University Institute of Engineering (UIE)


Reference

Fundamental of Computer Algorithms ,2nd Edition, Sartaj


Sahni, Ellis Horowitz, Sanguthevar Rajasekaran, Chapter
No.3 page no.145-152.

University Institute of Engineering (UIE)


Thanks

University Institute of Engineering (UIE)

You might also like