0
bool binsearch(int x) {
    int i = 0, j = N;
    while(i < j) {
        int m = (i+j)/2;
        if(arr[m] <= x) {
            if(arr[m] == x)
                return true;
            i = m+1;
        }
        else {
            j = m;
        }
    }
    return false;
}

This is my implementation of binary search which returns true if x is in arr[0:N-1] or returns false if x is not in arr[0:N-1].
And I'm wondering how can I figure out right loop invariant to prove this implementation is correct.
How can I solve this problem?
Thanks a lot :D

정희석
  • 9
  • 1
  • What have you researched so far about how to prove correctness of binary search so far? There should be a lot out there on he www. – MrSmith42 Jan 07 '20 at 08:49

1 Answers1

0

Think about the variables holding state within your loop. In your case, they are variables i and j. You start with the fact that all elements < i and less than the value you are searching for (x) and all elements > j and greater than the x. This is the invariant you are trying to maintain.

Shashank V
  • 10,007
  • 2
  • 25
  • 41