#include<iostream>
using namespace std;
int binary(int array[],int left,int right,int k)
{ if(left+1!=right)
{int i=(left+right)/2;cout<<left<<right<<endl;
if(k<=array[i]) {right=i;}
if(k>array[i]) {left=i;}
binary(array,left,right,k);
}
return right;
}
int main()
{cout<<"Pleased input an array storing 10 integers ordered by value(the left is least):"<<endl;
int a[10];
for(int i=0;i<10;i++)
cin>>a[i];
cout<<"What number do you want to search:"<<ends;
int se;
cin>>se;
cout<<se<<" is in the position of "<<binary(a,-1,10,se)<<endl;
return 0;
}
这个程序错在哪里啊???各位大虾救救。。
不好意思:补充一下,如果有相同的数存在,则输出第一个的位置。
用二分法查找一个已排好序的数组里面的某个值的位置?求!!!
答案:1 悬赏:0
解决时间 2021-02-23 11:27
- 提问者网友:巴黎塔下许过得承诺
- 2021-02-22 21:49
最佳答案
- 二级知识专家网友:没感情的陌生人
- 2021-02-22 22:35
我把你的程序改了改,你的问题在于递归函数要在最前边写出返回条件,而且二分法查找中,当left与right相等的时候,如果找不到要结束递归。
#include<iostream>
using namespace std;
int binary(int array[],int left,int right,int k)
{
int i= (left+right)/2;
// 数组中不存在这样的数
if ((left == right) && k != array[left])
{
printf ("not find\n");
exit (0);
}
// 找到相应的数
if (k == array[i])
return i; // C++ 中数组索引从0开始,不要搞混了
else
if (k < array[i]) // 查找左半边
{
right = i - 1;
binary(array, left, right, k);
}
else // 查找右半边
{
left = i + 1;
binary(array, left, right, k);
}
}
int main()
{
cout<<"Pleased input an array storing 10 integers ordered by value(the left is least):"<<endl;
int a[10];
for(int i=0;i<10;i++)
cin>>a[i];
cout<<"What number do you want to search:"<<ends;
int se;
cin>>se;
cout<<se<<" is in the position of "<<binary(a, 0, 10, se)<<endl; // 这里要改改
return 0;
}
#include<iostream>
using namespace std;
int binary(int array[],int left,int right,int k)
{
int i= (left+right)/2;
// 数组中不存在这样的数
if ((left == right) && k != array[left])
{
printf ("not find\n");
exit (0);
}
// 找到相应的数
if (k == array[i])
return i; // C++ 中数组索引从0开始,不要搞混了
else
if (k < array[i]) // 查找左半边
{
right = i - 1;
binary(array, left, right, k);
}
else // 查找右半边
{
left = i + 1;
binary(array, left, right, k);
}
}
int main()
{
cout<<"Pleased input an array storing 10 integers ordered by value(the left is least):"<<endl;
int a[10];
for(int i=0;i<10;i++)
cin>>a[i];
cout<<"What number do you want to search:"<<ends;
int se;
cin>>se;
cout<<se<<" is in the position of "<<binary(a, 0, 10, se)<<endl; // 这里要改改
return 0;
}
我要举报
如以上问答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯