« August 2021 »
August
MoTuWeThFrSaSu
1
2345678
9101112131415
16171819202122
23242526272829
3031
Uni-Logo
You are here: Home Teaching Summer Term 2017 Formal Methods for Java (Lecture) Resources Demos Lecture 14 InsertionSort.java
Document Actions

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.

InsertionSort.java — Java source code, 1Kb

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;
        }
    }
}
Personal tools