Professional Documents
Culture Documents
Divideandconquer 171108085822
Divideandconquer 171108085822
ALGORITHMS
1
Shashikant V. Athawale
Assistant Professor ,Computer Engineering Department
AISSMS College of Engineering,
Kennedy Road, Pune , MS, India - 411001
DIVIDE & CONQUER
2
THE DIVIDE AND CONQUER
ALGORITHM
Divide_Conquer(problem P)
{
if Small(P) return S(P);
else {
return Combine(Divide_Conque(P1),
Divide_Conque(P2),…, Divide_Conque(Pk));
}
} 3
DIVIDE AND CONQUER EXAMPLES
Merge sort
Quick sort
Binary Search
4
MERGE SORT
5
MERGE SORT
[25][57][48][37][12][92][86][33]
pass 1
[25 57][37 48][12 92][33 86]
pass 2
[25 37 48 57][12 33 86 92]
pass 3
[12 25 33 37 48 57 86 92]
log2n passes are required.
time complexity: O(nlogn)
6
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
7
A[i]≤p A[i] ≥ p
QUICK SORT
5 3 1 9 8 2 4 7
2 3 1 4 5 8 9 7
1 2 3 4 5 7 8 9
1 2 3 4 5 7 8 9
1 2 3 4 5 7 8 9
1 2 3 4 5 7 8 9
8
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
else lm+1 // the key is on the right half of the
array 9
return -1
Thank You
10