Lecture 007

Buggy Binary Search

Psudo Code

Psudo Code

Psudo Code w/ Midpoint

Psudo Code w/ Midpoint

int illiano_search(int x, int[] A, int n)
//@requires n == \length(A);
//@requires is_sorted(A, 0, n);
/*@ensures (\result == -1 && !is_in(x, A, 0, n))
|| (0 <= \result && \result < n && A[\result] == x);@*/
{
  int lo = 0;
  int hi = n;
  while (lo < hi)
  //@loop_invariant 0 <= lo && lo <= hi && hi <= n;
  //@loop_invariant gt_seg(x, A, 0, lo);
  //@loop_invariant lt_seg(x, A, hi, n);
  {
    int mid = (lo+hi)/2;
    if (A[mid] == n) return mid;
    if (A[mid] < n) {
        lo = mid+1;
    } else {
        hi = mid;
    }
  }
  //@assert lo == hi;
  return -1;
}

Full Binary Search

Full Binary Search

Table of Content