0
6.7kviews
Explain with example how divide and conquer stategy is used in binary search
1 Answer
1
259views

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.

  1. If KEY=A[m] then desired element is present in the list.

  2. Otherwise if KEY<a[m] then="" search="" the="" left="" sub="" list.<="" p="">

  3. Otherwise if KEY>A[m] then search the right sub list.

This can be represented as

enter image description here

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;

}

Please log in to add an answer.