BinarySearch method implements binary search algorithm. This method you can use in C/C++ program. Method takes integer array, array start position, array last element position, and value to search as input. Method returns position of the value to search in the array, if value not found then it returns -1.
As we know binary search algorithm can only be used for sorted arrays. In case if you wish to use binary search on an array which is not sorted then you must sort it using some sorting technique and then use binary search algorithm to find the desired element in the array.
int BinarySearch( int * intArray, int start, int end, int key)
{
while( start <= end )
{
int mid = (start + end)/2;
if( intArray[mid] == key)
return mid;
if( key < intArray[mid] )
end = mid - 1;
else
start = mid + 1;
}
return -1;
}
|
---|
Binary search can also be implemented in recursive way as below.
int RecBinarySearch( int * intArray, int start, int end, int key) { if( start <= end ) { int mid = (start + end)/2; if( intArray[mid] == key) { return mid; } else { if( key < intArray[mid] ) return RecBinarySearch( intArray, start, mid-1, key); else return RecBinarySearch( intArray, mid+1, end, key); } } else return -1; // Element not Found } |
---|
No comments:
Post a Comment