Loop invariant of linear search

前端 未结 7 1822
醉梦人生
醉梦人生 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:31

    Loop invariant would be

    forevery 0 <= i < k, where k is the current value of the loop iteration variable, A[i] != v

    On loop termination:

    if A[k] == v, then the loop terminates and outputs k

    if A[k] != v, and k + 1 == n (size of list) then loop terminates with value nil

    Proof of Correctness: left as an exercise

提交回复
热议问题