Loop invariant of linear search

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

    Assume that you have an array of length i, indexed from [0...i-1], and the algorithm is checking if v is present in this array. I'm not totally sure, but I think, the loop invariant is as follows: If j is the index of v, then [0..j-1] will be an array that does not have v.

    Initialization : Before iterating from 0..i-1, the current array checked (none), does not consist of v.

    Maintenance : On finding v at j, array from [0..j-1] will be an array without v.

    Termination : As the loop terminates on finding v at j, [0..j-1] will be an array without j.

    If the array itself does not have v, then j = i-1, and the above conditions will still hold true.

提交回复
热议问题