二进制搜索不适用于特定输出
Binary seach not working for a particular output
在二叉搜索中仅针对单个输入获得意外输出。当我在二进制搜索程序中输入 {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;
}
您的循环不正确。您正在更改循环中搜索的边界(beg
和last
(。因此,要检查您是否无法进一步搜索,您需要检查beg
是否已越过last
在这种情况下,您将停止搜索。
此外,在您的代码中,a
是使用new
分配的数组,但您调用的是delete a
而不是delete[] a
。
相关文章:
- FLTK 2.0构建和演示,适用于VS2019的2011年左右的代码库
- C++17 - 使用自定义分配器的节点提取/重新插入 - 适用于 clang++/libc++,但不适用于 libstd
- "string.h"在构建适用于iOS的qt应用程序中找不到消息
- 适用于 WebView2 旧版本的示例应用程序
- 在 NVIDIA GEFORCE GTX 1050 上下载适用于 Windows 10 的 openCL 1.2
- __attribute__(优化(0))) 是否适用于"recursively"?
- 为什么 std::erase(std::erase_if) 不是适用于<algorithm>任何容器的模板?
- 使用一个参数的模板函数时出错(适用于 2)
- 使用 适用于 Android 和 iOS 的 tf-lite C++ API
- 为什么这适用于 G++ 而不是 CLANG?
- 适用于 macOS 的 Xcode 应用程序。这就是我设置从USB麦克风输入获取音频的方式。一年前工作,现在没有了。为什么
- 适用于 Linux 的 c++ 上的代理脚本
- 为什么我的 SFINAE 表达式不再适用于 GCC 8.2?
- 使输出流式处理运算符适用于 boost::variant<std::vector<int>、int、double 的正确方法是什么>
- 有没有适用于Windows.lib文件的GNU二进制文件描述符(BFD)
- 模板函数仅适用于VS
- 如何在cmake中包含适用于g++或viceversa的库
- 适用于win32、linux、mac的POSIX C包装器
- WinDBG适用于从Visual Studio 2015保存的转储,但不适用于任务管理器。显示异常代码"not found"
- 如何通过C/ c++从Linux命令中获得输出?并且适用于android