Loop invariant of linear search

前端 未结 7 1751
醉梦人生
醉梦人生 2021-01-31 09:16

As seen on Introduction to Algorithms (http://mitpress.mit.edu/algorithms), the exercise states the following:

Input: Array A[1..n] and a v

7条回答
  •  孤城傲影
    2021-01-31 09:23

    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 ith 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 ith 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+1th).

    Termination: the for loop may end for two reasons:

    1. return i (line 3), if A[i] == ν;
    2. i == A.length + 1 (last test of the for loop), in which case we are at the beginning of the A.length + 1th 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.

提交回复
热议问题