二进制搜索不适用于特定输出

Binary seach not working for a particular output

本文关键字:输出 适用于 搜索 不适用 二进制      更新时间:2023-10-16

在二叉搜索中仅针对单个输入获得意外输出。当我在二进制搜索程序中输入 {1,2,3,4,5} 作为数组中的输入时,即使元素存在,它也会显示仅输入"2"不存在的元素。试码。

我尝试在迭代中跟踪代码,但我不明白为什么这不起作用以及变量(pos 是我的情况(值是否在更改。

#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;
}

您的循环不正确。您正在更改循环中搜索的边界(beglast(。因此,要检查您是否无法进一步搜索,您需要检查beg是否已越过last在这种情况下,您将停止搜索。

此外,在您的代码中,a是使用new分配的数组,但您调用的是delete a而不是delete[] a