Loop invariant of linear search
In the case of linear search, the loop variant will be the backing store used for saving the index(output) .
Lets name the backing store as index which is initially set to NIL.The loop variant should be in accordance with three conditions :
- Initialization : This condition holds true for index variable.since, it contains NIL which could be a result outcome and true before the first iteration.
- Maintenance : index will hold NIL until the item v is located. It is also true before the iteration and after the next iteration.As, it will be set inside the loop after comparison condition succeeds.
- Termination : index will contain NIL or the array index of the item v.
.
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
?
LINEAR-SEARCH(A, ν)
1 for i = 1 to A.length
2 if A[i] == ν
3 return i
4 return NIL
Loop invariant: at the start of the i
th iteration of the for
loop (lines 1–4),
∀ k ∈ [1, i) A[k] ≠ ν.
Initialization:
i == 1 ⟹ [1, i) == Ø ⟹ ∀ k ∈ Ø A[k] ≠ ν,
which is true, as any statement regarding the empty set is true (vacuous truth).
Maintenance: let's suppose the loop invariant is true at the start of the i
th iteration of the for
loop. If A[i] == ν
, the current iteration is the final one (see the termination section), as line 3 is executed; otherwise, if A[i] ≠ ν
, we have
∀ k ∈ [1, i) A[k] ≠ ν and A[i] ≠ ν ⟺ ∀ k ∈ [1, i+1) A[k] ≠ ν,
which means that the invariant loop will still be true at the start of the next iteration (the i+1
th).
Termination: the for
loop may end for two reasons:
return i
(line 3), ifA[i] == ν
;i == A.length + 1
(last test of thefor
loop), in which case we are at the beginning of theA.length + 1
th iteration, therefore the loop invariant is∀ k ∈ [1, A.length + 1) A[k] ≠ ν ⟺ ∀ k ∈ [1, A.length] A[k] ≠ ν
and the
NIL
value is returned (line 4).
In both cases, LINEAR-SEARCH
ends as expected.