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.
low + high / 2will calculatelow + (high / 2)due to operator precedence but you need(low + high) / 2in order to calculate the middle.