美文网首页
简单易懂的二分查找

简单易懂的二分查找

作者: HeoLis | 来源:发表于2019-05-16 11:38 被阅读0次
    //
    // 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;
    }
    

    相关文章

      网友评论

          本文标题:简单易懂的二分查找

          本文链接:https://www.haomeiwen.com/subject/uwgbaqtx.html