binary search code implementation

Function: Query the position of a value in an array of length n.

Time complexity: log2(n)

The following algorithm should be used on sorted arrays (in ascending order), returning the index of the last number in the range [left, right) less than or equal to e.

EG:  b[5] = {1, 2, 3, 3, 5};    find(0, 5, 3) = 4 

array

int find(int left,int right, ll e) {
    int mid;
    while(left < right) {
        mid = (left+right)/2;
        (e < b[mid]) ? right = mid : left = mid + 1; // The array b[] is a global variable, which can be changed according to actual usage
    }
    return left-1;
}

Use a question to verify:

Topic link: Portal

Reference Code:

#include <iostream>
#include <cstdio>
using namespace std;
typedef long long ll;
const int N = 200100;
ll a[N];
ll b[N];
int find(int left,int right, ll e) {
    int mid;
    ++right;
    while(left < right) {
        mid = (left+right)/2;
        (e < b[mid]) ? right = mid : left = mid + 1;
    }
    return left-1;
}
intmain()
{
    int n, m;
    ll sum = 0;
    cin >> n >> m;
    b[0] = 0;

    for(int i=1;  i<=n; ++i) {
        scanf("%I64d", &a[i]);
        sum += a[i];
        b[i] = a[i] + b[i-1];
    }

    ll now = 0, temp;
    int cnt = 0;

    for(int i=1; i<=m; ++i) {
        scanf("%I64d", &temp);
        now += temp;

        if(now >= sum) {
            cout << n << endl;
            now = 0;
            continue;
        }

        cnt = find(0, n, now);
        if(b[cnt] - now > 0)
            cout << n-cnt+1 << endl;
        else
            cout << n-cnt << endl;
    }
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326074294&siteId=291194637