Lecture 005

Simple Search Mechanism

int search(int x, int[] A, int n)
//@requires n == \length(A);
/*@ensures \result == -1
|| (0<=\result&&\result<n && A[\result]) == x;
@*/
{
  for (int i = 0; i < n; i++)
  //@loop_invariant 0 <= i;
  {
    if (A[i]==x) return i;
  }
  return -1;
}

Fixing contract exploit

Fixing contract exploit

int search(int x, int[] A, int n)
//@requires n == \length(A);
/*@ensures \result == -1 && !is_in(x, A, 0, n)
|| (0<=\result&&\result<n && A[\result]) == x;
@*/
{
  for (int i = 0; i < n; i++)
  //@loop_invariant 0 <= i;
  {
    if (A[i]==x) return i;
  }
  return -1;
}

Proof:

A code that satisfy correctness by editing array

return may not be the first index

Testing

Edge cases

Mishandled:

- stress test with big inputs

TODO: why?

Table of Content