Kirarrr

导航

二分查找

#include <cstdio>

int binarySearch(int a[], int left, int right, int x) {
    int mid;
    while (left <= right) {
        mid = (left + right) / 2;
        if (a[mid] == x) return mid;
        else if (a[mid] > x) {
            right = mid - 1;
        } else {
            left = mid + 1;
        }
    }
    return - 1;
}

int main() {
    const int n = 10;
    int a[n] = {1, 3, 4, 6, 7, 8, 10, 12, 15};
    printf("%d %d\n", binarySearch(a, 0, n - 1, 6), binarySearch(a, 0, n - 1, 9));
    return 0;
}

posted on 2019-01-31 01:02  Kirarrr  阅读(54)  评论(0编辑  收藏  举报