What is a loop invariant?

后端 未结 15 1345
后悔当初
后悔当初 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:32

    In simple words, a loop invariant is some predicate (condition) that holds for every iteration of the loop. For example, let's look at a simple for loop that looks like this:

    int j = 9;
    for(int i=0; i<10; i++)  
      j--;
    

    In this example it is true (for every iteration) that i + j == 9. A weaker invariant that is also true is that i >= 0 && i <= 10.

提交回复
热议问题