I am trying to learn about loop invariants in C. I have a code and I have the loop invariant but I do not fully understand why. Here is the code:
/* 0 ≤ m < n < ASIZE AND A[m] ≥ A[m+1] ≥ ... ≥ A[n] */
void ReverseArray(int A[], int m, int n)
{
int temp;
while (m < n)
{
temp = A[m]; A[m] = A[n]; A[n] = temp;
m++;
n--;
/* loop invariant: 0 < m < n < ASIZE OR m == n OR m == n+1 */
}
}
/* for the initial values of m and n, A[m] ≤ A[m+1] ≤ ... ≤ A[n] */
The loop invariant is: 0 < m < n < ASIZE OR m == n OR m == n+1
I think I understand the 0 < m < n < ASIZE. It would be because of the while loop and it says that m cant be 0 but it has to be less than n. And n has to be smaller than the array size.
But I do not understand why m == n and m == n+1.
Any thoughts?