小编han*_*ans的帖子

二进制搜索查找排序数组中的最低和最大元素而不是给定值?

所以,我试图实现二进制搜索算法(尽可能通用,可以适应不同的情况).我在互联网上搜索过这个,有些使用,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 …
Run Code Online (Sandbox Code Playgroud)

c++ algorithm binary-search

3
推荐指数
1
解决办法
4794
查看次数

标签 统计

algorithm ×1

binary-search ×1

c++ ×1