What is a loop invariant?

后端 未结 15 1378
后悔当初
后悔当初 2020-11-28 17:13

I\'m reading \"Introduction to Algorithm\" by CLRS. In chapter 2, the authors mention \"loop invariants\". What is a loop invariant?

15条回答
  •  无人及你
    2020-11-28 17:35

    In Linear Search (as per exercise given in book), we need to find value V in given array.

    Its simple as scanning the array from 0 <= k < length and comparing each element. If V found, or if scanning reaches length of array, just terminate the loop.

    As per my understanding in above problem-

    Loop Invariants(Initialization): V is not found in k - 1 iteration. Very first iteration, this would be -1 hence we can say V not found at position -1

    Maintainance: In next iteration,V not found in k-1 holds true

    Terminatation: If V found in k position or k reaches the length of the array, terminate the loop.

提交回复
热议问题