我的代码如下不起作用,没有给我任何输出。当我要求用户输入一组数字并在其中查找时,它运行良好。但是,当我尝试在随机数字内搜索时,它根本不起作用。任何人都可以帮我弄清楚,我做错了什么,因为程序构建成功。它只是不会给出正确的输出。使用二进制搜索算法搜索随机数中的数字集
{
class program
{
public class BinarySearch
{
public static int Search(int[] list, int x, int lower, int upper)
{
if (lower == upper)
{
int middle = (lower + upper)/2;
if (x == list[middle])
return middle;
else if (x > list[middle])
return Search(list, x, lower, middle - 1);
else
return Search(list, x, middle + 1, upper);
}
return 0;
}
public static void Main(String[] args)
{
int key;
int index;
int low = 0;
int high = 1000;
int[] list = new int[1000];
Random RandomNumber = new Random();
for (int i = 0; i < 1000; i++)
{
list[i] = RandomNumber.Next(1, 1000);
}
foreach (int j in list)
{
Console.WriteLine("{0}", j);
}
Console.WriteLine("...................................................\n");
Console.WriteLine("\nEnter the number to be searched in the list.");
key = Convert.ToInt32(Console.ReadLine());
index = Search(list, key, low, high);
Console.WriteLine("...................................................\n");
if (index == 0)
Console.WriteLine("Key {0} not found", key);
else
Console.WriteLine("Key {0} found at index {1}", key, index);
}
}
}
}
二进制搜索模仿人类搜索词汇的方式。尝试搜索一个未排序的;) –