Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimize Binary Search Algorithm

In a binary search, we have two comparisons one for greater than and other for less than, otherwise its the mid value. How would you optimize so that we need to check only once?

bool binSearch(int array[], int key, int left, int right)
{

    mid = left + (right-left)/2;
    if (key < array[mid])
        return binSearch(array, key, left, mid-1);
    else if (key > array[mid])
        return binSearch(array, key, mid+1, right);
    else if (key == array[mid])
        return TRUE; // Found

    return FALSE; // Not Found
}
like image 602
Ganesh M Avatar asked Nov 26 '22 22:11

Ganesh M


1 Answers

I would try the bsearch() standard function first. Chances are good that it performes better than your approach.

like image 85
quinmars Avatar answered Dec 10 '22 10:12

quinmars