算法正确性证明的三要素
1)invariant property 是什么,每步循环保证了invariant property
2)证明循环可以退出:(比如,在循环体的每个分支,循环的界都是在收敛)
3)根据循环退出的condition和 invariant property 得出answer
/*
invariant property: the min is within the range [l, r]
loop can stop: each loop the range is reduced
loop exit condition: the range has one element, or is monotonic, and we
have the invariant property the min is in the range, so it has to be num[l]
*/
int findMin(vector<int> &num) {
int l = 0, r = num.size() - 1;
while (l < r && num[l] >= num[r]) {
int mid = l + (r - l) / 2;
if (num[mid] > num[r])
l = mid + 1;
else if (num[mid] < num[r])
r = mid;
else
r--;
}
return num[l];
}