简单易懂的二分查找

字数 0阅读 9
//
// Created by heolis on 19-5-16.
//
#include <bits/stdc++.h>

using namespace std;

/*
 * A[]:严格递增序列
 * left:二分下界
 * right:二分上界
 * x:要查询的数
 * 注意:二分区间为左闭右闭区间
 */
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, 11, 12, 15};
    printf("%d %d\n", binarySearch(A, 0, n - 1, 6), binarySearch(A, 0, n - 1, 9));
    
    return 0;
}

推荐阅读更多精彩内容