This repository has been archived on 2023-06-18. You can view files and clone it, but cannot push or open issues or pull requests.
soft-an01/selectionsort.dfy

48 lines
1,009 B
Text
Raw Normal View History

2023-03-27 16:16:22 +00:00
predicate sorted(s: seq<int>)
{
2023-03-26 20:38:58 +00:00
forall i,j: int :: 0 <= i < j < |s| ==> s[i] <= s[j]
}
2023-03-27 16:16:22 +00:00
predicate sameElements(a: seq<int>, b: seq<int>)
{
multiset(a) == multiset(b)
}
2023-03-26 20:38:58 +00:00
method SelectionSort(a: array<int>)
modifies a
2023-03-27 16:16:22 +00:00
ensures sorted(a[..])
ensures sameElements(a[..], old(a[..]))
2023-03-26 20:38:58 +00:00
{
if (a.Length == 0) {
return;
}
var s := 0;
while (s < a.Length - 1)
2023-03-27 16:16:22 +00:00
invariant sameElements(a[..], old(a[..]))
2023-03-26 20:38:58 +00:00
invariant forall i,j: int :: 0 <= i < s <= j < a.Length ==> a[i] <= a[j]
invariant s <= a.Length - 1
invariant s >= 1 ==> sorted(a[0..s])
decreases a.Length - s
{
var min: int := s;
var i: int := s + 1;
while i < a.Length
2023-03-27 16:16:22 +00:00
invariant sameElements(a[..], old(a[..]))
2023-03-26 20:38:58 +00:00
invariant s <= min < a.Length
invariant s + 1 <= i <= a.Length
invariant forall j: int :: s <= j < i ==> a[min] <= a[j]
decreases a.Length - i
{
if (a[i] < a[min]) {
min := i;
}
i := i + 1;
}
a[s], a[min] := a[min], a[s];
s := s + 1;
}
}