Binary search and invariant relation

后端 未结 3 1428
终归单人心
终归单人心 2021-02-04 21:16

I\'m reading this post and trying to figure out how could we determine invariant relation for binary search. To be specific, in the two examples he gave, why these two invariant

3条回答
  •  别那么骄傲
    2021-02-04 21:50

    You wrote

    The part A[start] < target < A[end] is obvious

    but it's obviously wrong because initial values should be start = 0, end = N-1 (not -1, N). BTW, you don't need any invariant for the case described in your link (array of distinct elements).

    This will work without problems and easy to understand.

    int arr[] = {0,1,2,3,4,5,6,7};
    int N = sizeof (arr) / sizeof (arr[0]);
    int target = 4;
    
    int l = 0, r = N-1;
    while( l <= r ) {
        int mid = (l+r)>>1;
        if( arr[mid] == target )
            return mid;
        if( arr[mid] < target )
            l = mid + 1;
        else
            r = mid - 1;
    }
    return -1; // not found
    

提交回复
热议问题