/* Search, as developed in class * 15-122, Fall 2010, CMU */ bool is_in(int x, int[] A, int n) //@requires 0 <= n && n <= \length(A); { int i; for (i = 0; i < n; i++) //@loop_invariant 0 <= i && i <= n; if (A[i] == x) return true; return false; } bool is_sorted(int[] A, int n) //@requires 0 <= n && n <= \length(A); { int i; for (i = 0; i < n-1; i++) //@loop_invariant n == 0 || (0 <= i && i <= n-1); if (!(A[i] <= A[i+1])) return false; return true; } int linsearch(int x, int[] A, int n) //@requires 0 <= n && n <= \length(A); //@requires is_sorted(A,n); //@ensures (\result == -1 && !is_in(x, A, n)) || A[\result] == x; { int i; for (i = 0; i < n && A[i] <= x; i++) //@loop_invariant 0 <= i && i <= n; //@loop_invariant i == 0 || A[i-1] < x; if (A[i] == x) return i; return -1; } int binsearch(int x, int[] A, int n) //@requires 0 <= n && n <= \length(A); //@requires is_sorted(A,n); //@ensures (\result == -1 && !is_in(x, A, n)) || A[\result] == x; { int lower = 0; int upper = n; while (lower < upper) //@loop_invariant 0 <= lower && lower <= upper && upper <= n; //@loop_invariant (lower == 0 || A[lower-1] < x) && (upper == n || A[upper] > x); { int mid = lower + (upper-lower)/2; // (lower + upper)/2 could overflow if (A[mid] == x) return mid; else if (A[mid] < x) lower = mid+1; else /*@assert(A[mid] > x);@*/ upper = mid; } return -1; }