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;
}
Table of Content