递归二进制搜索有问题吗? [英] Problem with recursive binary search?
问题描述
为什么我的递归二进制搜索代码不起作用?找不到搜索总是返回元素.
例如:如果有5个元素-4、8、13、17和21.搜索17将返回没有找到的元素.
Why my code for recursive binary search not working? The search always return element is not found.
For example: If there are 5 elements - 4, 8, 13, 17, and 21. Search for 17 return no element found.
#include<iostream>
using namespace std;
int midind, elements, first=0 , last=(elements-1);
int array1[5];
bool searches (int index , int search)
{
if (index>=elements|| index<=0)
{
cout<<"The number "<<search<<" was not found!! \n";
return false;
}
else if (search==array1[index])
{
cout<<"The number "<<search<<" was found and its index is "<<index<<" \n";
return true;
}
else if (search>array1[index])
{
first= index;
index= static_cast<int>((first+last)*0.5);
return searches (index, search);
}
else if (search<array1[index])
{
last = index;
index = static_cast<int>((first+last)*0.5);
return searches (index , search);
}
}
void main ()
{
int i, search;
cout<<"Enter the number of elements of your integer array \n";
cin>>elements;
cout<<"Enter the "<<elements<<" elements of your integer array in ascending order \n";
for (i=0 ; i<elements ; i++)
{
cin>>array1[i];
}
cout<<endl<<"Your integer array is:"<<endl;
for (i=0 ; i<elements ; i++)
{
cout<<array1[i];
cout<<"\t";
}
cout<<endl<<endl;
cout<<"Enter a number to search for: \n";
cin>>search;
midind= static_cast<int>((first+last)*0.5);
searches (midind , search);
}
推荐答案
int midind,elements,first = 0,last =(elements-1);
int midind, elements, first=0 , last=(elements-1);
上面的语句没有任何意义,应该向编译器发出警告.您不能在elements
包含任何值之前从elements
设置last
.
The above statement makes no sense, and should give a compiler warning. You cannot set last
from elements
before elements
contains any value.
您的基本问题似乎是第一个条件:
Your basic problem seems to be the first condition:
if (index>=elements|| index<=0)
第一次运行时,索引始终为< = 0(您自己将其设置为0)
将条件更改为:
In the first run index will always be <= 0 (you set it to 0 yourself)
Change the condition to:
if (index>=elements|| index<0)
但是理查德的观点也是有效的,对谁打败他的人我都会说::thumbsdown:并且:X |
But Richard''s point is also valid and to whoever downvoted him I say: :thumbsdown: and also: X|
谢谢理查德先生! :)........
Thanks you Mr. Richard! :)........
这篇关于递归二进制搜索有问题吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!