Reputation: 575
This is pseudocode for a linear search in an array, returning an index i
if the desired element e
in an array A
is found, NIL
otherwise (this is from the CLRS book, 3rd edition, exercise 2.1-3):
LINEAR_SEARCH (A, e)
for i = 1 to A.length
if A[i] == e
return i
return NIL
I'm trying to extrapolate a loop invariant from it, so according to my understanding I think that one is represented by the fact that at any given moment in the loop the sub-array A[1..i-1]
only contains values for which the equality test proves false.
Specifically, before the first iteration i-1 == 0
which implies that the sub-array's length is null, therefore there cannot be an element v
belonging to it such that v == e
. Before any next iteration, being the equality test an exit condition as well, the supposed invariant property must still hold true, otherwise the loop would have already ended. On termination, it's either that the function is about to return an index (and in that case the loop invariant is trivially true), or that NIL is returned (in that case i == A.length + 1
, so the loop invariant holds true for any 1 < j < i
).
Is the above correct? Could you please provide a correct loop invariant in case it is not?
Thanks for your attention.
Upvotes: 0
Views: 170
Reputation: 48129
Loop invariant: At the start of each iteration of the for loop we have A[j] != e
for all j < i
.
Initialization: Before the first loop iteration the invariant holds since the array is empty.
Maintenance: The loop invariant is maintained at each iteration, since otherwise at the i
-th iteration there is some j < i
such that A[j] == e
. However, in that case for the j
-th iteration of the loop the value j
is returned, and there is no i
-th iteration of the loop, a contradiction.
Termination When the loop terminates, there may be two cases: one is that it terminates after i <= A.length
iterations, and returns i
, in which case the if
conditional ensures that A[i] == e
. The other case is that i
exceeds A.length
, in this case by the loop invariant we have that for all j <= A.length
, A[j] != e
, this returning NIL is correct.
Upvotes: 1