Consider the searching problem:
Input: A sequence of n numbers A = <a1, a2,…,an>and a value v.
Output: An index i such that A[i] = v or the special value NIL if v does not
appear 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.
伪代码:
LINEAR_SEARCH(A , v)
for i=1 to n
do if A[i] = v
then return i
i = i + 1
return NIL
利用循环不变式证明:
我们可以断言:对于任意 x < i ,A[i] != v为真