-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathtasks_2019.dfy
110 lines (103 loc) · 1.79 KB
/
tasks_2019.dfy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
// Dafny coursework tasks
// Autumn term, 2019
//
// Authors: John Wickerson and Matt Windsor
// Task 1
predicate sorted(A:array<int>)
reads A
{
forall m,n :: 0 <= m < n < A.Length ==> A[m] <= A[n]
}
// Task 2
method bubble_sort(A:array<int>)
ensures sorted(A)
modifies A
{
var i := 0;
while i < A.Length {
var j := 1;
while j < A.Length - i {
if A[j-1] > A[j] {
A[j-1], A[j] := A[j], A[j-1];
}
j := j+1;
}
i := i+1;
}
}
// Task 3
method selection_sort(A:array<int>)
ensures sorted(A)
modifies A
{
var i := 0;
while i < A.Length {
var k := i;
var j := i+1;
while j < A.Length {
if A[k] > A[j] {
k := j;
}
j := j+1;
}
A[k], A[i] := A[i], A[k];
i := i + 1;
}
}
// Task 4
method insertion_sort(A:array<int>)
ensures sorted(A)
modifies A
{
var i := 0;
while i < A.Length {
var j := i;
var tmp := A[j];
while 1 <= j && tmp < A[j-1] {
A[j] := A[j-1];
j := j-1;
}
A[j] := tmp;
i := i+1;
}
}
// Task 5
method shellsort(A:array<int>)
modifies A
ensures sorted(A)
{
var stride := A.Length / 2;
while 0 < stride {
var i := 0;
while i < A.Length {
var j := i;
var tmp := A[j];
while stride <= j && tmp < A[j-stride] {
A[j] := A[j-stride];
j := j-stride;
}
A[j] := tmp;
i := i+1;
}
stride := stride / 2;
}
}
// Task 6
method john_sort(A:array<int>)
modifies A
ensures sorted(A)
{
var i := 0;
while i < A.Length {
A[i] := 42;
i := i + 1;
}
}
method Main() {
var A:array<int> := new int[7] [4,0,1,9,7,1,2];
print "Before: ", A[0], A[1], A[2], A[3],
A[4], A[5], A[6], "\n";
bubble_sort(A);
print "After: ", A[0], A[1], A[2], A[3],
A[4], A[5], A[6], "\n";
}