Loop invariants are properties of the algorithm or structure that are always true at particular points in the program. Within a loop's body these properties may become violated briefly, but the rest of the loop's instructions fix these properties for the next iteration.
Loop invariants are used in an inductive proof to formally validate the "correctness" of an algorithm. For a loop invariant to be used in a proof features of the code being analyzed must be used to demonstrate that any violations of the loop invariant are restored before the next iteration.
To determine the loop invariant we can roughly follow these steps
int minIndex(vector<int>& arr, int a) {
int m = a;
for (int i = a+1; i < arr.size(); i++) {
if (arr[i] < arr[m]) {
m = i;
}
}
return m;
}
Firstly, we can read through the code and see that it only updates m to be the current index if the element at the current index is smaller than the element at the index m. We can roughly determine then that our exampleFunction returns the index smallest element after a, or a if the element at a is the smallest already.
Running through a few examples we can see that m is always the index of the smallest element of the processed array so far.
Loop Invariant: m is the index of the minimum element in the arr[a..i-1] at the start of the iteration i for all
Base Case: i=a+1
m contains the index of the smallest element of arr[a..a]int m = a;Inductive Step: i = k, a + 1 <= k < arr.size()
k, ie. m contains the index of the smallest element of arr[a..k-1]arr[k] < arr[m]
arr[k] is smaller than any element of arr[a..k-1]m is set to k, and contains the index of the smallest element of arr[a..k], thus loop invariant holds after processing index karr[k] is not smaller than the smallest element of arr[a..k-1]m contains the index of the smallest element of arr[a..k], thus the loop invariant holds after processing index kTermination: i=arr.size()
m contains the index of the smallest element of arr[a..arr.size()-1]a to arr.size()-1m contains the index of the smallest element in the entire subarrayarr.size() is finite, and i increments each iteration towards arr.size() the program must terminate.