Divide and Conquer: Binary Search
Divide and Conquer: Binary Search
Following are some standard algorithms that are Divide and Conquer algorithms.
1) Binary Search is a searching algorithm. In each step, the algorithm compares the input element x
with the value of the middle element in array. If the values match, return the index of middle.
Otherwise, if x is less than the middle element, then the algorithm recurs for left side of middle
element, else recurs for right side of middle element.
2) Quicksort is a sorting algorithm. The algorithm picks a pivot element, rearranges the array
elements in such a way that all elements smaller than the picked pivot element move to left side of
pivot, and all greater elements move to right side. Finally, the algorithm recursively sorts the subarrays
on left and right of pivot element.
3) Merge Sort is also a sorting algorithm. The algorithm divides the array in two halves, recursively
sorts them and finally merges the two sorted halves.
4) Closest Pair of Points The problem is to find the closest pair of points in a set of points in x-y
plane. The problem can be solved in O(n^2) time by calculating distances of every pair of points and
comparing the distances to find the minimum. The Divide and Conquer algorithm solves the problem
in O(nLogn) time.
5) Strassens Algorithm is an efficient algorithm to multiply two matrices. A simple method to multiply
two matrices need 3 nested loops and is O(n^3). Strassens algorithm multiplies two matrices in
O(n^2.8974) time.
Binary Search
int binary_search(int A[], int key, int imin, int imax)
{
// test if array is empty
if (imax < imin)
// set is empty, so return value showing not found
return KEY_NOT_FOUND;
else
{
// calculate midpoint to cut set in half
int imid = midpoint(imin, imax);
// three-way comparison
if (A[imid] > key)
// key is in lower subset
return binary_search(A, key, imin, imid - 1);
else if (A[imid] < key)
// key is in upper subset
return binary_search(A, key, imid + 1, imax);
else
// key has been found
return imid;
}
}
Analysis
Binary Search can be accomplished in logarithmic time in the worst case ,
i.e., T(n) = (log
in the best case.
imax = imid - 1;
}
// key was not found
return KEY_NOT_FOUND;
}
Analysis
The analysis of Iterative algorithm is identical to that of its recursive counterpart.