I have to do insertion sort with recursion and prove its correctness by using a loop invariant. I am confident that my code is correct and it works with different inputs. But, I don't know how to prove its correctness the way my book does. Can someone prove it is correct by using a loop invariant ?
The algorithms are proved correct in the book by using the steps below which are similar to mathematical induction. If needed, refer enter link description here
1 - Find the loop invariant for each loop in your algorithm. The loop invariant is a condition which is true before the start of the loop, after any of the subsequent iterations and upon termination of the loop.
2 - Use logic to prove that the loop invariants are true prior before loop initialization, are maintained in subsequent loop runs and are true when the loop has terminated.
//n - The index till which the array D is to be sorted.
public static void sort(int n, int [] D){
if(n == 0){
return;
}else {
sort(n-1, D);
}
int lastItem = D[n];
int j = n-1;
while (j >= 0 && lastItem < D[j]) {
D[j + 1] = D[j];
j--;
}
//Insert the lastItem at the correct position.
D[j+1] = lastItem;
}
}
PS - The book I use is "Introduction to Algorithms" by Thomas Cormen i.e. the CLRS book.