'Binary search with recursion c#
I got stuck with my binary search method and I don't really know what I'm doing.
At this moment I got
1 Error (CS0161) not all code paths return a value
int low = 0;
int high = cities.Length;
static int BinarySearch(City[] cities, int key, int low, int high)
{
int mid;
if (low > high)
return -1; //Sökning EJ hittad
mid = low + high / 2;
if (key == cities[mid].temp)
return mid; //Sökning Hittad!
else if (key < cities[mid].temp)
BinarySearch(cities, key, low, mid - 1);
else
BinarySearch(cities, key, mid + 1, high);
}
...searching for temperature with input from user.
Console.WriteLine("\n\tBINARY SEARCH\n");
do
{
Console.Write("Search temp:");
loop = true;
str = Console.ReadLine();
try
{
key = Convert.ToInt32(str);
index = BinarySearch(cities, key, low, high);
if (index == -1)
{
Console.WriteLine($"Couldn't find any city with temperature: {key}°C");
}
else
{
Console.WriteLine("Search results: ");
Console.WriteLine(cities[index].ToString());
loop= false;
}
}
catch
{
Console.WriteLine("Only numbers, please.");
}
} while (loop);
Solution 1:[1]
The error message 'not all code paths return a value
' is correct:
if (key == cities[mid].temp)
return mid; //Sökning Hittad!
else if (key < cities[mid].temp)
BinarySearch(cities, key, low, mid - 1); // <-- does not return anything
else
BinarySearch(cities, key, mid + 1, high); // <-- does not return anything
Fix:
if (key == cities[mid].temp)
return mid; //Sökning Hittad!
else if (key < cities[mid].temp)
return BinarySearch(cities, key, low, mid - 1);
else
return BinarySearch(cities, key, mid + 1, high);
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 | Fildor |