因此,每当我尝试搜索 A[0] 元素(在本例中为 23)时。它不返回元素的位置。但是,当我尝试搜索 A[0] 之后的其他元素时,它工作正常。请告诉我代码有什么问题,我该如何解决。 示例输出-- 输入要搜索的项目 - 23 输出- 在此数组中找不到元素 23。 提前致谢!
#include <iostream>
using namespace std;
int main(){
int A[]= {23, 34, 45, 67, 75, 89};
int I= sizeof(A)/sizeof(A[0]);
int LAST= I-1, FIRST= 0, MID, ITEM, INDEX= 0;
MID= ((FIRST + LAST)/2);
cout<<"Enter item to search- ";
cin>>ITEM;
while(FIRST <= LAST){
if(A[MID] == ITEM){
INDEX= MID;
break;
}
else if(A[MID] < ITEM){
FIRST= MID+1;
}
else{
LAST= MID-1;
}
MID= ((FIRST + LAST)/2);
}
if(INDEX != 0){
cout<<"\nElement "<<ITEM<<" found at position "<<(INDEX+1);
}
else{
cout<<"\nElement "<<ITEM<<" could not be found in this array.";
}
}
最佳答案
if(INDEX >= 0){
cout<<"\nElement "<<ITEM<<" found at position ".
<<(INDEX+1);
}
索引在数组中从 0 开始。因此,修改 IF 条件以检查 INDEX >= 0。如果未找到输入元素,则 INDEX 将返回 -1。
关于c++ - 二进制搜索代码找不到数组的 A[0] 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45906797/