简体   繁体   中英

How do I implement binary search for an array of integers?

I want to implement binary search for an array of integers. I made sure that array sorted incrementally. But my function is not tracking all the cases and some of the checks fail. What am I missing here? Value stands for integer I'm trying to find.

bool search(int value, int array[], int n)
{   
    int left = 0;
    int right = n - 1;
    int middle = (left + right) / 2;

while (right >= left)
{
    if (array[middle] == value)
    return true;
    else if (array[middle] < value)
    right = middle;
    else if (array[middle] > value)
    left = middle + 1;

    middle = (left + right) / 2;
}

return false;
} 

My guess is that some left or right border cases are not predicted. I also not strong about while condition.

You mixed left and right, if array[middle] < value you have to change left .

bool search(int value, int array[], int n)
{
    int left = 0;
    int right = n - 1;
    int middle = left + (right - left) / 2;

    while (right >= left)
    {
        if (array[middle] == value)
            return true;
        else if (array[middle] > value)
            right = middle - 1;
        else if (array[middle] < value)
            left = middle + 1;

        middle = (left + right) / 2;
    }
    return false;
}

will work: http://ideone.com/VSAhnZ

Further improvements can be:

  1. You can exclude middle in the else parts, because you have already proved that it is not the correct value ( right = middle; => right = middle - 1; )

  2. The second else if can be replaced by an else . If it is not the value and not smaller you do not have to test if it is larger.

Standard binary search algorithm can be found anywhere. but just correcting your code:

bool search(int value, int array[], int n)
{   
    int left = 0;
    int right = n - 1;
    int middle;
    while (left <= right)
    {
         middle = (left + right) / 2;    
        if (value > array[middle] )
            left = middle + 1;
        else if (value < array[middle])
            right = middle - 1;                
        else 
            return true;
     }
     return false;
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM