Skip to content

Commit 80bca2e

Browse files
committed
added quicksort example
1 parent 4ef211c commit 80bca2e

1 file changed

Lines changed: 77 additions & 0 deletions

File tree

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
/**
2+
* This shows how MultiSets can be used to verify the permutation property
3+
* of a sorting algorithm.
4+
* FIXME: The sortedness property is NOT shown.
5+
* The source code is the same as quicksort/QuickSort.java but the present
6+
* specification is proven automatically, without proof scripts.
7+
*
8+
* @author Silvia Zoraqi, Lukas Grätz, 2025
9+
*
10+
* based on:
11+
* @author Mattias Ulbrich, 2015
12+
*/
13+
14+
class Quicksort {
15+
16+
/*@ public normal_behaviour
17+
@ ensures (\mset int k; 0 <= k < array.length; array[k]) == \old((\mset int k; 0 <= k < array.length; array[k]));
18+
@ assignable array[*];
19+
@*/
20+
public void sort(int[] array) {
21+
if(array.length > 0) {
22+
sort(array, 0, array.length-1);
23+
}
24+
}
25+
26+
/*@ public normal_behaviour
27+
@ requires 0 <= from;
28+
@ requires to < array.length;
29+
@ ensures (\mset int k; 0 <= k < array.length; array[k]) == \old((\mset int k; 0 <= k < array.length; array[k]));
30+
@ assignable array[*];
31+
@ measured_by to - from + 1;
32+
@*/
33+
private void sort(int[] array, int from, int to) {
34+
if(from < to) {
35+
int splitPoint = split(array, from, to);
36+
sort(array, from, splitPoint-1);
37+
sort(array, splitPoint+1, to);
38+
}
39+
}
40+
41+
/*@ public normal_behaviour
42+
@ requires 0 <= from && from < to && to <= array.length-1;
43+
@ ensures (\mset int k; 0 <= k < array.length; array[k]) == \old((\mset int k; 0 <= k < array.length; array[k]));
44+
@ ensures from <= \result && \result <= to;
45+
@ assignable array[*];
46+
@*/
47+
private int split(int[] array, int from, int to) {
48+
49+
int i = from;
50+
int pivot = array[to];
51+
52+
/*@
53+
@ loop_invariant from <= i && i <= j;
54+
@ loop_invariant from <= j && j <= to;
55+
@ loop_invariant (\mset int k; 0 <= k < array.length; array[k]) == \old((\mset int k; 0 <= k < array.length; array[k]));
56+
@ decreases to + to - j - i + 2;
57+
@ assignable array[*];
58+
@*/
59+
for(int j = from; j < to; j++) {
60+
if(array[j] <= pivot) {
61+
int t = array[i];
62+
array[i] = array[j];
63+
array[j] = t;
64+
i++;
65+
}
66+
}
67+
68+
// FIXME: this assignment has no effect, it should be a loop invariant
69+
pivot = array[to];
70+
71+
array[to] = array[i];
72+
array[i] = pivot;
73+
74+
return i;
75+
76+
}
77+
}

0 commit comments

Comments
 (0)