I'm attempting to learn the loop invariant technique to produce more efficient algorithms. My understanding of proving correctness through evaluating loop invariants is that the loop invariants must be true before iteration, and after iteration, to confirm the wanted output.
In the case of the algorithm I put together below (sorting a sequence in decreasing order)- this is the property I believe satifies confirmation of correctness:
"Target would be sequence is decreasing such that A[j] > A[i] for all i from 0 to j-1"
I also think i >=0 and i < A.length would be loop invariants in this case.
In examing the three steps for loop invariants (initialization, maintenance, termination)...does what I came up with make sense in this context? I feel like I'm still not quite understanding how to apply the concept in this instance.
static void Sort(int array[]) {
int size = array.length;
for (int i = 0; i < size - 1; i++)
for (int j = i + 1; j < size; j++)
if (array[j] > array[i]) {
// swapping elements.
int buffer = array[j];
array[j] = array[i];
array[i] = buffer;
}