0

I am always wondering how to prove the correctness of a simple program. For example, a interview problem like First Missing Positive. The program looks like this:

public class Solution{
    public int firstMissingPositive(int[] A){
        int i = 0;
        while(i < A.length){
            if(A[i] != (i+1) && A[i] >= 1 && A[i] <= A.length && A[A[i]-1] != A[i]){
                int tmp = A[A[i]-1];
                A[A[i]-1] = A[i];
                A[i] = tmp;
            }
            else{
                i++;
            }
        }
        for(i = 0; i < A.length; i++){
            if(A[i] != (i+1))
                return i+1;
        }
        return A.length+1;
    }
}

How to construct the invariant for this program? What is the general tips for construct the invariant for simple algorithm?

  • 1
    We have all been wondering this for sixty years. – Bruce David Wilner Jul 13 '16 at 16:44
  • You can replace the `if` by another `while` and remove the `else`, so the invariant for the outer `while` becomes trivial, but the invariant for the new inner `while` is harder to find. – maraca Jul 13 '16 at 21:57

0 Answers0