-
Notifications
You must be signed in to change notification settings - Fork 1
/
088-sort_array.dfy
86 lines (83 loc) · 2.2 KB
/
088-sort_array.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
method sort_array(s: seq<int>) returns (sorted: seq<int>)
// post-conditions-start
ensures |sorted| == |s|
ensures |s| > 0 && (s[0] + s[|s| - 1]) % 2 == 0 ==>
forall i, j :: 0 <= i < j < |sorted| ==> sorted[i] >= sorted[j]
ensures |s| > 0 && (s[0] + s[|s| - 1]) % 2 != 0 ==>
forall i, j :: 0 <= i < j < |sorted| ==> sorted[i] <= sorted[j]
// post-conditions-end
{
// impl-start
if |s| == 0 {
sorted := [];
} else if (s[0] + s[|s| - 1]) % 2 == 0 {
var t := SortSeq(s);
sorted := reverse(t);
return;
} else {
sorted := SortSeq(s);
return;
}
// impl-end
}
method reverse(s: seq<int>) returns (rev: seq<int>)
// post-conditions-start
ensures |rev| == |s|
ensures forall k :: 0 <= k < |s| ==> rev[k] == s[|s| - 1 - k]
// post-conditions-end
{
// impl-start
rev := [];
var i := 0;
while (i < |s|)
// invariants-start
invariant i >= 0 && i <= |s|
invariant |rev| == i
invariant forall k :: 0 <= k < i ==> rev[k] == s[|s| - 1 - k]
// invariants-end
{
rev := rev + [s[|s| - i - 1]];
i := i + 1;
}
// impl-end
}
method SortSeq(s: seq<int>) returns (sorted: seq<int>)
// post-conditions-start
ensures forall i, j :: 0 <= i < j < |sorted| ==> sorted[i] <= sorted[j]
ensures |sorted| == |s|
ensures multiset(s) == multiset(sorted)
// post-conditions-end
{
// impl-start
sorted := s;
var i := 0;
while i < |sorted|
// invariants-start
invariant 0 <= i <= |sorted|
invariant forall j, k :: 0 <= j < k < i ==> sorted[j] <= sorted[k]
invariant multiset(s) == multiset(sorted)
invariant forall j :: 0 <= j < i ==> forall k :: i <= k < |sorted| ==> sorted[j] <= sorted[k]
invariant |sorted| == |s|
// invariants-end
{
var minIndex := i;
var j := i + 1;
while j < |sorted|
// invariants-start
invariant i <= minIndex < j <= |sorted|
invariant forall k :: i <= k < j ==> sorted[minIndex] <= sorted[k]
// invariants-end
{
if sorted[j] < sorted[minIndex] {
minIndex := j;
}
j := j + 1;
}
if minIndex != i {
var temp := sorted[i];
sorted := sorted[i := sorted[minIndex]][minIndex := temp];
}
i := i + 1;
}
// impl-end
}