You are here: Home Demos Lecture 14 InsertionSort.java

InsertionSort.java

The bug was in the return type of the function. The function was declared as returning int, but it didn't return. After changing the return type to void the verification succeeded.

Plain Text icon InsertionSort.java — Plain Text, 1 kB (1306 bytes)

File contents

public class InsertionSort {

    /*@ requires array != null;
      @ ensures (\forall int k1,k2; 0 <= k1&& k1 <= k2 && k2 < array.length;
      @          array[k1] <= array[k2]);
      @ modifies array[*];
      @*/
    public void sort(int[] array) {
        /*@ loop_invariant 1 <= i;
          @ loop_invariant (\forall int k1,k2; 0 <= k1&& k1 <= k2 && k2 < i;
          @                 array[k1] <= array[k2]);
          @ decreases array.length - i+1;
          @ modifies array[*];
          @*/
        for (int i = 1; i < array.length; i++) {
            int t = array[i];
            int j = i-1; 
            /*@ loop_invariant 1 <= i && i < array.length;
              @ loop_invariant -1 <= j && j < i;
              @ loop_invariant (\forall int k1,k2; 
              @                 0 <= k1 && k1 <= k2 && k2 <= (j == i-1 ? i-1 : i);
              @                 array[k1] <= array[k2]);
              @ loop_invariant t <= array[j+1];
              @ decreases j + 1;
              @ modifies array[*];
              @*/
            while (j >= 0) {
                if (array[j] > t) {
                    array[j + 1] = array[j];
                } else {
                    break;
                }
                j--;
            }
            array[j+1] = t;
        }
    }
}