'Binary Search with recursive algorithm

Another problem here! I've been coding a Binary Search with recursive algorithm. Now it seems to be some problem when it search in upper half of the array. I can't really find whats wrong.

//=====Binary Search=====//
static int BinarySearch(City[] cities, int key, int low, int high)
{
    int mid;

    if (low > high)
    {
        return -1;
    }

    mid = low + high / 2;

    if (key == cities[mid].temp)
    {
        return mid;
    }
    else if (key < cities[mid].temp)
    {
        return BinarySearch(cities, key, low, mid - 1);
    }
    else
    {
        return BinarySearch(cities, key, mid +1, high);
    }
}

When I search for a number that can't be found it will print: "can't find temperature". It is doing its work as long as I don't search for a number in the upper half.

Console.WriteLine("\n\tBINÄR SÖKNING\n");
do
{
    loop = true;
    Console.Write("search temperature:");
    str = Console.ReadLine();
    
    try
    {
        key = Convert.ToInt32(str);
        
        index = BinarySearch(cities, key, low, high);

        if (index == -1)
        {
            Console.WriteLine($"can't find temperature: {key}°C");
        }
        else
        {
            Console.WriteLine("");
            Console.WriteLine(cities[index].ToString());
            loop = false;
        }
    }
    catch
    {
        Console.WriteLine("Only numbers, please");
    }
} while (loop);

If I search for a number in the upper half, the console will print "Only numbers, please". It goes to the catch-part. as it should if I search for something that can NOT convert to int.



Solution 1:[1]

Operator precedence bites again.

How is the expression low + high / 2 parsed?

Probably not the way you think. Multiplicative operators have higher precedence than additive operators, so

low + high / 2

gets parsed as

low + (high / 2)

rather than your intended

(low + high) / 2

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nicholas Carey