DIVIDE & CONQUER
ALGORITHMS
Shashikant V. Athawale
Assistant Professor ,Computer Engineering Department
AISSMS College of Engineering,
Kennedy Road, Pune , MS, India - 411001
1
DIVIDE & CONQUER
The most well known algorithm design strategy:
1.Divide the problem into two or more smaller
subproblems.
2.Conquer the subproblems by solving them
recursively.
3.Combine the solutions to the subproblems into
the solutions for the original problem.
2
THE DIVIDE AND CONQUER
ALGORITHM
Divide_Conquer(problem P)
{
if Small(P) return S(P);
else {
divide P into smaller instances P
1
, P
2
, …,
P
k
, k³1;
Apply Divide_Conquer to each of these
subproblems;
return Combine(Divide_Conque( P
1
),
Divide_Conque(P
2
),…, Divide_Conque(P
k
));
}
} 3
MERGE SORT
The merge sort algorithm works from “the
bottom up”
start by solving the smallest pieces of the main
problem
keep combining their results into larger solutions
eventually the original problem will be solved
5
QUICK SORT
Select a pivot whose value we are going to divide the
sublist. (e.g., p = A[l])
Rearrange the list so that it starts with the pivot
followed by a ≤ sublist (a sublist whose elements are
all smaller than or equal to the pivot) and a ≥ sublist
(a sublist whose elements are all greater than or equal
to the pivot ) (See algorithm Partition in section 4.2)
Exchange the pivot with the last element in the first
sublist(i.e., ≤ sublist) – the pivot is now in its final
position
Sort the two sublists recursively using quicksort.
p
A[i]≤p A[i] ≥ p
7
BINARY SEARCH
ALGORITHM
BinarySearch(A[0..n-1], K)
//Implements nonrecursive binary search
//Input: An array A[0..n-1] sorted in ascending order and
// a search key K
//Output: An index of the array’s element that is equal to K
// or –1 if there is no such element
l 0, r n – 1
while l £ r do //l and r crosses over can’t find
K.
m ë(l + r) / 2û
if K = A[m] return m //the key is found
else
if K < A[m] r m – 1//the key is on the left half of the
array
elsel m + 1// the key is on the right half of
the array
return -1
9