As seen on Introduction to Algorithms (http://mitpress.mit.edu/algorithms), the exercise states the following:
Input: Array A[1..n]
and a value v
Output: Index i
, where A[i] = v
or NIL
if v
does not found in A
Write pseudocode for LINEAR-SEARCH, which scans through the sequence, looking for v. Using a loop invariant, prove that your algorithm is correct. (Make sure that your loop invariant fulfills the three necessary properties – initialization, maintenance, termination.)
I have no problem creating the algorithm, but what I don't get is how can I decide what's my loop invariant. I think I understood the concept of loop invariant, that is, a condition that is always true before the beginning of the loop, at the end/beginning of each iteration and still true when the loop ends. This is usually the goal, so for example, at insertion sort, iterating over j
, starting at j = 2
, the A[1..j-1]
elements are always sorted. This makes sense to me. But for a linear search? I can't think of anything, it just sounds too simple to think of a loop invariant. Did I understand something wrong? I can only think of something obvious like (it's either NIL or between 0 and n). Thanks a lot in advance!
After you have looked at index i
, and not found v
yet, what can you say about v
with regard to the part of the array before i
and with regard to the part of the array after i
?