仅针对二进制搜索中的单个输入获取意外输出。当我在二进制搜索程序的数组中输入{1,2,3,4,5}作为输入时,即使元素存在,它也只显示输入'2'而不显示元素。尝试使用代码块。
我曾尝试在迭代中跟踪代码,但我不明白为什么它不起作用以及变量(以我的情况为准)值是否在更改。
#include <iostream>
using namespace std;
int main()
{
int last,fin,beg=0,mid,pos=-1,i,*a;
cout<<"Enter the size of array: ";
cin>>last;
a=new int[last];
cout<<"Enter the elements in array"<<endl;
for(i=0;i<last;i++)
{
cin>>a[i];
}
cout<<endl<<"Enter the element you want to find: ";
cin>>fin;
for(i=beg;i<=last;i++)
{
mid=(beg+last)/2;
if(a[mid]==fin)
{
pos=mid;
}
else if(a[mid]>fin)
{
last=mid-1;
}
else
{
beg=mid+1;
}
}
if(pos==-1)
{
cout<<"Element not present in array"<<endl;
}
else
{
cout<<"element found "<<fin<<" at "<<pos+1<<" position"<<endl;
}
delete a;
return 0;
}
我希望输出2应该是:当我将size(最后变量)输入为5并将元素输入为1,2,3,4,5时,在2位置找到2的元素。我正在得到输出:数组中不存在元素。
将循环更改为此:
while (beg <= last) {
int mid = (beg + last) / 2;
if (a[mid] == fin) {
pos = mid;
break; // break where you find the element in the array
}
else if (a[mid] > fin) last = mid - 1;
else beg = mid + 1;
}
您的循环不正确。您正在循环中更改搜索范围(beg
和last
)。因此,要检查是否无法继续搜索,需要检查beg
是否越过last
,您将停止搜索。
而且,在您的代码中,a
是使用new
分配的数组,但是您正在调用delete a
而不是delete[] a
。