Binary search and invariant relation

后端 未结 3 1429
终归单人心
终归单人心 2021-02-04 21:16

I\'m reading this post and trying to figure out how could we determine invariant relation for binary search. To be specific, in the two examples he gave, why these two invariant

3条回答
  •  野性不改
    2021-02-04 21:48

    The answer to your question is the answer to the question "What is a loop invariant".

    The whole point of a loop invariant is to provide a useful property before, during, and (probably most importantly) after the termination of the loop. As an example, insertion sort has a loop invariant that the array to be sorted is in sorted order for a range that starts at 1 index (one item is always sorted), and grows to be the entire array. The usefulness of this is that if its true before the loop starts, and the loop doesn't violate it, you can infer correctly that after the execution of the loop the entire array is sorted. Assuming you didn't mess up your termination condition, which doesn't violate the loop invariant because the invariant only refers to a subarray of the entire array, which may or may not be the entire array. If you terminate early, the subarray is less than the entire array, but the subarray is guaranteed to be sorted, per the invariant.

    The post you linked says much the same, though it would probably be better if the author actually explained more about what he was talking about. The article seems to seek to teach, yet leaves much unsaid that should be said, even if just as a footnote to more in-depth information for those who are curious or need more information.

    To answer your question "why are the two invariants different" directly, the answer is because they are solving two different problems.

    A couple of quotes from your link that illustrate this:

    • I emphasize once again, the invariant relation guides us coding.
    • Finding the invariant relation of the problem, and then everything becomes easy.

提交回复
热议问题