written 7.8 years ago by | • modified 7.8 years ago |
Binary search is an efficient searching method. While searching the elements using this method the most essential thing that the elements in the array should be sorted one.
An element which is to be sorted from the list of elements sorted in array should be sorted one.
An element which is to be searched from the list of elements stored in array A[0…n-1] is called KEY element.
Let A[m] be the mid element of array A. then there are three conditions that needs to be tested while searching the array using this method.
If KEY=A[m] then desired element is present in the list.
Otherwise if KEY<a[m] then="" search="" the="" left="" sub="" list.<="" p="">
Otherwise if KEY>A[m] then search the right sub list.
This can be represented as
Algorithm:
i=binary(x,key);
where x is the array having n elements sorted in ascending order and key is the element to be searched.
binary(int x[], int key)
{
int low, high, mid;
low=0; high=x.length-1;
while(low<=high)
{
mid=(low+high)/2;
if(key==x[mid])
return (mid);
else if (key<x[mid])< p="">
high=mid-1;
else
low=mid+1;
}
return -1;
}