The document discusses divide and conquer algorithms. It describes divide and conquer as a design strategy that involves dividing a problem into smaller subproblems, solving the subproblems recursively, and combining the solutions. It provides examples of divide and conquer algorithms like merge sort, quicksort, and binary search. Merge sort works by recursively sorting halves of an array until it is fully sorted. Quicksort selects a pivot element and partitions the array into subarrays of smaller and larger elements, recursively sorting the subarrays. Binary search recursively searches half-intervals of a sorted array to find a target value.
DIVIDE & CONQUER
ALGORITHMS
ShashikantV. Athawale
Assistant Professor ,Computer Engineering Department
AISSMS College of Engineering,
Kennedy Road, Pune , MS, India - 411001
1
2.
DIVIDE & CONQUER
Themost 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
3.
THE DIVIDE ANDCONQUER
ALGORITHM
Divide_Conquer(problem P)
{
if Small(P) return S(P);
else {
divide P into smaller instances P1, P2, …,
Pk, k≥1;
Apply Divide_Conquer to each of these
subproblems;
return Combine(Divide_Conque(P1),
Divide_Conque(P2),…, Divide_Conque(Pk));
}
} 3
MERGE SORT
Themerge 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
Selecta 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)
//Implementsnonrecursive 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
else l m + 1 // the key is on the right half of
the array
return -1
9