# 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;
}

• however, the function might not return what we expected. We add "if we return -1, x is not in array"

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:

• Correctness:

• Correctness:

A code that satisfy correctness by editing array

• so adding a deep copy? - no, we don't need to write 100% contract

• so we need testing

return may not be the first index

## Testing

Edge cases

• first element in an array

• last element of an array

• empty array

• 1 element array

Mishandled:

• sorted arrays: values that are too small, too big, just right

TODO: why?

Table of Content