Proving Correctness of A Routine
Proving Correctness of A Routine
Proving a routine, or more formally, verifying the correctness of an algorithm or a procedure involves
several steps. The proof ensures that the routine behaves as expected for all possible inputs. This
1. Specification: Clearly define what the routine is supposed to do. This includes:
- Input: The type and range of inputs the routine will handle.
2. Correctness:
- Partial Correctness: Prove that if the routine terminates, then it produces the correct output. This
- Termination: Prove that the routine always terminates. This often involves demonstrating that
3. Invariants: Identify invariants (conditions that remain true throughout the execution of the routine).
- Initialization: Show that the invariant is true before the routine starts.
- Maintenance: Show that if the invariant is true before an iteration of the routine, it remains true
- Termination: Show that the invariant and the termination condition together imply that the
postcondition holds.
Proving the Correctness of a Routine
4. Inductive Proofs: Many routines, especially recursive ones, can be proved correct using
mathematical induction.
Specification:
- Postconditions: The output array A is sorted such that for all i and j where 1 <= i <= j <= n, A[i] <=
A[j].
for j = 2 to A.length
key = A[j]
i=j-1
A[i + 1] = A[i]
i=i-1
A[i + 1] = key
Proof of Correctness:
Proving the Correctness of a Routine
Initialization:
- Before the first iteration of the outer loop, the subarray A[1..1] is trivially sorted.
Maintenance:
- Assume that the subarray A[1..j-1] is sorted before the j-th iteration of the outer loop.
- During the j-th iteration, the element A[j] (stored in key) is inserted into the correct position in the
sorted subarray A[1..j-1] by shifting larger elements one position to the right.
Termination:
- The outer loop runs from j = 2 to j = n. At the end of the loop, j = n + 1, so the entire array A[1..n] is
sorted.
Termination Proof:
- The inner loop decreases the value of i from j - 1 to 0, ensuring that each element is compared and
placed correctly.
- Thus, both loops will terminate, and the algorithm will complete its execution.
Conclusion:
By using invariants and the principles of induction, we have shown that Insertion Sort correctly sorts
an array. The routine terminates and satisfies the postcondition that the array is sorted.
This is a basic example of proving the correctness of a routine. More complex routines may require
Proving the Correctness of a Routine
more intricate proofs, including handling edge cases and proving more sophisticated invariants.