/* Selection sort (quadratic) * Frank Pfenning, Fall 2010 */ bool beloweq(int x, int[] A, int lower, int upper) //@requires 0 <= lower && lower <= upper && upper <= \length(A); { int i; for (i = lower; i < upper; i++) //@loop_invariant lower <= i && i <= upper; if (!(x <= A[i])) return false; return true; } bool is_sorted(int[] A, int lower, int upper) //@requires 0 <= lower && lower <= upper && upper <= \length(A); { int i; for (i = lower; i < upper-1; i++) //@loop_invariant lower == upper || (lower <= i && i <= upper-1); if (!(A[i] <= A[i+1])) return false; return true; } void swap(int[] A, int i, int j) //@requires 0 <= i && i < \length(A); //@requires 0 <= j && j < \length(A); // modifies A[i], A[j]; //@ensures A[i] == \old(A[j]) && A[j] == \old(A[i]); { int tmp = A[i]; A[i] = A[j]; A[j] = tmp; } /* Selection sort (in place) * Result is permutation because we only swap elements of A * Complexity is quadratic */ void selsort(int[] A, int lower, int upper) //@requires 0 <= lower && lower <= upper && upper <= \length(A); //@ensures is_sorted(A, lower, upper); { int i; int j; for (i = lower; i < upper; i++) // i = upper-1 is redundant, but inv's are easier.. //@loop_invariant lower <= i && i <= upper; //@loop_invariant is_sorted(A, lower, i); //@loop_invariant i == lower || beloweq(A[i-1], A, i, upper); { int min = i; for (j = i+1; j < upper; j++) //@loop_invariant i+1 <= j && j <= upper; //@loop_invariant beloweq(A[min], A, i, j); if (A[j] < A[min]) min = j; // swap A[i] and A[min] swap(A, i, min); } }