1.

Write an algorithm for Binary search. What are the conditions under which sequential search of a list is preferred over binary search? 

Answer»

Algorithm for Binary Search:- 

Assuming that a [] is the array of items to be searched, n is the number of items in the array a, and target is the value of the item that is to be searched. 

int binsearch( int target, int a[], int n)

{

int low=0; 

int high=1; 

int mid; 

while (low<=high) 

{

mid=(low+high)/2;

if (target==a[mid])

return (mid);

if (target<a[mid])

high=mid-1;

else

low=mid+1;

return (-1);

}

Sequential search is preferred over binary search in the following conditions:- 

i). If the list is short sequential search is easy to write and efficient than binary search. 

ii) If the list is unsorted then binary search cannot be used, in that case we have to use sequential search. 

iii) If the list is unordered and haphazardly constructed, the linear search may be the only way to find anything in it. 



Discussion

No Comment Found

Related InterviewSolutions