Reviewing is_sorted
Reviewing is_in
Analyzing linear search
The function is_sorted is what we call a specification function.
This function isn't meant to be run on its own to solve a problem. Instead
it's typically used in an annotation for another function to check for
correctness when we need it. For example, when we do linear search on a
sorted array, how do we know that the array is sorted when the function
starts? We can call this specification function to check it for us, but
only if we're doing dynamic runtime testing using the -d option.
The following function returns true if the first n elements of the array A
are sorted in non-decreasing order (i.e. for any element, the next element
is either the same or increasing). It returns false otherwise.
When we talked about an array being
sorted, we will usually mean this unless we specify otherwise.
Some points to consider:
In this case, since n could be 0, we need to explicitly test for this
otherwise the rest of the invariant would be false and the code would
cause an annotation failure. In this case, the order that we test
the two separate conditions for n and i does not
matter, even with short-circuit evaluation. But we tend to write the
special case first (n == 0) and then the general case next.
The return statement in C0 returns immediately from the
function, even if additional statements follow it. So if we find
a pair of adjacent array values that are not in the correct order,
we don't need to check the rest of the array since the array can't
possibly be sorted, so we immediately return false. If we get through
the whole loop without returning false, then when we exit, we return
true.
Since this is being treated as a specification function, we generally
do not write postconditions for this function.
Reviewing is_sorted
bool is_sorted(int[] A, int n)
//@requires 0 <= n && n <= \length(A);
{
for (int 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;
}
Remember that the loop invariant must include the value of the loop
variable i when the loop condition is tested the last time (i.e. when
the loop is about to terminate.