Loop invariant of linear search

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

    The LS algorithm that I wrote is-

    LINEARSEARCH(A, v)
      for i=0 to A.length-1
        if(A[i] == v)
          return i
      return NIL
    

    I made my own assumptions for loop invariant for checking correctness of Linear Search:

    1. At Initialisation- at i = 0, we are searching for v at i = 0.

    2. At successive iterations- we are looking for v till i < A.length-1

    3. At termination- i = A.length and till A.length we kept looking for v.

    0 讨论(0)
提交回复
热议问题