当我运行这个程序并输入一个值来搜索程序崩溃时(exe
已停止工作,关闭程序)。一旦输入值 65,我得到一个 Number not found 无限循环输入要搜索的值(-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;
}