【发布时间】:2016-02-01 00:30:47
【问题描述】:
所以,我试图实现二进制搜索算法(尽可能通用,可以适应不同的情况)。我在互联网上搜索了这个,有些使用while (low != high),有些使用while (low <= high),以及其他一些非常令人困惑的不同条件。
因此,我开始编写代码来查找大于给定元素的第一个元素。我想知道是否有比这更优雅的解决方案?
主要代码:
#include <iostream>
#include <map>
#include <vector>
#include <string>
#include <utility>
#include <algorithm>
#include <stack>
#include <queue>
#include <climits>
#include <set>
#include <cstring>
using namespace std;
int arr1[2000];
int n;
int main (void)
{
int val1,val2;
cin>>n;
for (int i = 0; i < n; i++)
cin>>arr1[i];
sort(arr1,arr1+n);
cout<<"Enter the value for which next greater element than this value is to be found";
cin>>val1;
cout<<"Enter the value for which the first element smaller than this value is to be found";
cin>>val2;
int ans1 = binarysearch1(val1);
int ans2 = binarysearch2(val2);
cout<<ans1<<"\n"<<ans2<<"\n";
return 0;
}
int binarysearch1(int val)
{
while (start <= end)
{
int mid = start + (end-start)/2;
if (arr[mid] <= val && arr[mid+1] > val)
return mid+1;
else if (arr[mid] > val)
end = mid-1;
else
start = mid+1;
}
}
类似地,为了找到小于给定元素的第一个元素,
int binarysearch2(int val)
{
while (start <= end)
{
int mid = start + (end-start)/2;
if (arr[mid] >= val && arr[mid] < val)
return mid+1;
else if (arr[mid] > val)
end = mid-1;
else
start = mid+1;
}
}
当我必须修改二进制搜索以实现这种抽象时,我经常会感到非常困惑。请让我知道是否有更简单的方法?谢谢!
【问题讨论】:
-
请告诉我您已经为这些任务创建了一个函数...发布完整代码。
-
如果没有这样的元素,预期的行为是什么?
-
如果没有这样的元素,它应该返回 -1。我在编写这种二进制搜索时感到困惑,因此我不知道在哪里写它。分开怎么办?
-
@KarolyHorvath,添加了完整的代码。
-
搜索
lower_bound()和upper_bound()。
标签: c++ algorithm binary-search