问题描述
- 折半查找程序,输入后就崩溃,谁能帮忙看一下
-
#include
#include
using namespace std;
int half(int,vector );
int low=0;
int high=7;
int main(){
int b[10]={1,10,15,17,18,21,22,35,54,65};
vector a(b,b+10);
cout<<"请输入要査找的数:";
int number;
cin>>number;
if(half(number,a)){
cout<<"ok";
}
return 0;
}int half(int number,vector <int> a){ int mid=(high-low)/2; if(number>a[mid]){ a[low]=a[mid+1]; half(number,a); } else if(number<a[mid]){ a[high]=a[mid-1]; half(number,a); } else if (number==a[mid]){ return 1; } }
解决方案
a[high]=a[mid-1],这样做完全没有意义吧。应该是high=mid-1,对于low也是low=mid+1
解决方案二:
half函数可能没有返回值,前两个if,else应加上return语句
时间: 2024-12-27 21:46:41