How can I simplify this working binary search code in C?

Hey guys started programming in C a few weeks ago, learning about algothiritms, just wondering how you would make my code simpler, its just a binary search function. But the only thing you should leave the arguments the same, thanks in advance.

bool search(int value, int values[], int n)
{
    int min = values[0];
    int max = values[n-1];
    int average = (min + max) / 2;

    if(average == value)
    {
        return true;
    }

    while (average > value) 
    {
        max = average - 1;
        average = (min + max) / 2;

    }

    while (average < value)
    {
        min = average + 1;
        average = (min + max) / 2;
    }

    if (max < min) 
    {
        return false;
    }
    if (average == value) {
         printf("%i\n", average);
        return true;
    }
    else
    {
        return false;
    }
}
-3
source share
2 answers

This is not a proper implementation of binary search, all conditions must be in one cycle, for example: Also max must be n-1, not the values ​​[n-1] and min = 0 instead of the values ​​[0], and you must compare the values ​​of [ average] with the value of not only the average variable.

 bool search(int value, int values[], int n){

    int min = 0;
    int max = n-1;
    int average ;

    while(max>=min){
        average = (min + max) / 2;
        if(values[average] == value)
        {
            return true;
        }

        if (values[average] > value) 
        {
            max = average - 1;
            average = (min + max) / 2;

        }

       if (values[average] < value)
        {
            min = average + 1;
            average = (min + max) / 2;
        }

    }

    return false;
}
+4
source

, : length = 0, , , , (.. `(low + high)/2 ' ), , ..

, , , :

bool search(int[] array, int length, int valueToFind)
{
    int pos=0;
    int limit=length;
    while(pos<limit)
    {
        int testpos = pos+((limit-pos)>>1);

        if (array[testpos]<valueToFind)
            pos=testpos+1;
        else
            limit=testpos;
    }
    return (pos < length && array[pos]==valueToFind);
}

, , , , 2. , , , , , , , , , .

, testpos, , pos <= testpos < limit, AND , .

, , , high<low. , pos==limit, ..

, ", x, , xs, ", " x ", " x " ..

+3

Source: https://habr.com/ru/post/1687665/


All Articles