2.
4 Binary Search|
Q.4 Write recursive and non recursive algorithm for binary search
using divide and conquer method
Ans.: Algorithm (Non-recursive)
Algorithm BinSearch(A[0...n-1]KEY)
I/Problem Description: This algorithm is for searching the
//element using binary search method.
/Input: An aray A from which the KEY element is to be
//searched.
//Output: It returns the index of an array element if it is
/equal to KEY otherwise it returms -1
low-0
high-n-1
while (low<high) do
m-(low+high)/2//mid ofthe arrayis obtained
if (KEY=A/m]}then
return m
else if(KEY<A[m]}then
high- m-1 //search the left sub list
else
low -m+1 /search the right sub list
return-1 //if element is not present in the list
Design &Analysis of Algorithms 2-9 Divide and Conquer and Greedy Method
Algorithm (Recursive)
Algorithm BinSearch(A,KEY,low.high)
I/Problem Description: This algorithm is for searching the //element
using binary search method
I/Anput: A is an array of elements in which the desired
l/element is to be searched
I/KEY is the element that has to be searched
//Output: It returns the index of the array element if the KEY element
is found.
I/initially low=0; and high=n-1 where n is total number
l/ of elements in the list
m=(low+high)/2; //mid of the array is obtained
if(KEY=Am))then
retum mn;
else if(KEY<A[m}) then
BinSearch(A,KEY,low.m-1)://search the left sub list
else
BinSearch(A,KEY,m+1,high);//search the right sub list