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.