当我运行此程序并输入一个值以搜索程序崩溃时(exe
已停止工作,关闭程序)。一次输入值65时,我找到一个未找到的无限循环,输入一个值进行搜索(-1退出):
这是代码:
#include <iostream>
using namespace std;
void Search(int[], int * , int * );
int main()
{
int i,KEY,num, array[] = {98,87,76,65,54};
for(i=0;i<5;i++)
cout << array[i] << " ";
Search(array, &KEY, &num);
cout << endl;
system("pause");
return 0;
}
void Search(int arr[5], int * current, int * numel)
{
int low, high,search,N;
cout << "nWhat Number would you like to search for? (-1 to quit) : ";
cin >> search;
while(search!=-1)
{
low=0;
high=N-1;
while(low<=high)
{
*current=(low+high)/2;
if (search > arr[*current])
low=*current+1;
else if(search<arr[*current])
high=*current-1;
else
break;
}
if(arr[*current]==search)
cout << "Number found at index " << *current << endl;
else
cout << "Number not found." << endl;
cout << "Enter a value to search (-1 to quit) :";
}
return;
}
对于初学者来说,如果不在数组中的数字中,则Search
中的主循环是没有办法的。
然后,您正在使用high
之前使用任何值。
可能还有其他问题。您是如何在开发时测试的?
N
未初始化,所以谁知道这个说法:
high=N-1;
会做?