【发布时间】:2022-11-13 21:38:39
【问题描述】:
当我运行我的代码并从用户以升序输入数组时,我运行的函数会运行,如果我从数组中搜索中间数字以找到它的位置,则代码运行得非常好。但是当我从不在中间的数组中搜索数字时,代码没有给我任何输出,请解决这个问题。
#include<iostream>
using namespace std;
void input_array(int arr[], int n);
int binary_search(int arr[], int n, int target);
int main()
{
int limit;
cout<<"Enter The Limit For An Array:- ";
cin>>limit;
int arr[limit];
input_array(arr, limit);
int target;
cout<<"Enter The Number to find its position:- ";
cin>>target;
binary_search(arr, limit, target);
}
void input_array(int arr[], int n)
{
cout<<"Enter The Number in Increasing Order "<<endl;
for (int i = 0; i < n; i++)
{
cout<<i+1<<". Enter Number :- ";
cin>>arr[i];
}
}
int binary_search(int arr[], int n, int target)
{
int low = 0;
int high = n-1;
int mid;
for (int i = 0; i < n; i++)
{
mid = (low+high) / 2;
if (arr[mid] == target)
{
cout<<"The Position of The Given Target is :- "<<mid;
return 0;
}
if (arr[mid] > target)
{
low = mid + 1;
}
else
{
high = mid - 1;
}
}
return -1;
}
我创建了一个无法正常工作的程序,我不知道它无法正常工作的原因,请解决我的问题,以便我可以继续进行。
【问题讨论】:
-
请不要标记多种语言,只标记您实际编程的语言。问题是代码也不是有效的 C++,因为C++ doesn't have variable-length arrays。请改用
std::vector。 -
你的逻辑是相反的:如果数组中间的值(
arr[mid])大于target,那么这意味着你应该检查前半部分(high = mid - 1),但你检查的是后半部分(low = mid + 1) -
此外,当您进行二进制搜索时,您不能真正将其称为“二进制”功能“。你还记得数据需要*排序*才能使二进制搜索工作的重要要求吗?
-
也请花一些时间阅读the help pages,接受SOtour,阅读How to Ask,以及this question checklist。并了解如何edit您的问题以改进它们。
标签: c++ arrays data-structures binary-search array-algorithms