0

Here I have implemented the binary search in 2 ways, the iterative way, and the recursive way, but I get the same error for both ways, I also have implemented a insertion sort which works. but I am not sure why am I getting this error. Here are the code,

// using the iterative way
bool binarySearch2 (int value, int values[],int n)
{
    int min = 0;
    int max = n;
    while (max > min)
    {

        int mid = max + min / 2;
        if (values[mid] == value)
            return true;
        else if (values[mid] > value)
            max = mid - 1;
        else if (values[mid] < value)
            min = mid + 1;
    }

    return false;
}

or...

// using the recursive way
bool binarySearch(int value, int values[], int min, int max)
{
    int mid = max + min / 2;
    // making sure the target is in the list
    if (min > max)
        return false;

    else
    {
        // left half of the array
     if (values[mid] > value)
        binarySearch(value,values,min,mid - 1);
        // right half of the array
    else if (values[mid] < value)
        binarySearch(value,values,mid + 1, max);

    else 
        return true;    
    }

    return 0;    
}

and here is the insertion sort

void sort(int values[], int n)
{
    // insertion algorithm

    for (int i = 0; i < n; i++)
    {
        int element = values[i];
        int j = i;

        while(j > 0 && values[j - 1] > element)
        {
            values[j] = values[j - 1];
            j--;
        }
        values[j] = element;
    }

}
0
max + min / 2;

Division takes precedence over addition. What you are doing here is dividing the min by two then adding it to the max. Use parenthesis to add the max and min before dividing them by 2.

(max + min) / 2;
| improve this answer | |

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .