我的代碼如下不起作用,沒有給我任何輸出。當我要求用戶輸入一組數字並在其中查找時,它運行良好。但是,當我嘗試在隨機數字內搜索時,它根本不起作用。任何人都可以幫我弄清楚,我做錯了什麼,因爲程序構建成功。它只是不會給出正確的輸出。使用二進制搜索算法搜索隨機數中的數字集
{
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);
}
}
}
}
二進制搜索模仿人類搜索詞彙的方式。嘗試搜索一個未排序的;) –