0

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.

3
  • You should catch specific error type and print the error out while debugging rather than do a blind catch-all. Commented May 9, 2022 at 17:04
  • 1
    low + high / 2 will calculate low + (high / 2) due to operator precedence but you need (low + high) / 2 in order to calculate the middle. Commented May 9, 2022 at 17:05
  • Check out this answer for the simplest implementation of recursive Binary Search using C# 12. Commented Jan 28, 2024 at 21:12

1 Answer 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
Sign up to request clarification or add additional context in comments.

2 Comments

Okey. This made it work to search for a number in upper half that's IN the array. But still if I search for a number that's NOT in the array, (searching upper half) the program ends upp in catch { Console.WriteLine("Only numbers, please"); }
How are you computing the initial value of high? The first element of an array arr is arr[ 0 ], and the last is arr[ arr.Length - 1 ].. if you are setting the initial value of high to cities.Length, you will get an index out of range exception.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.