# Program verification

We did some program verification! See the lecture capture for details; here’s the Dafny code we ended up with.

```predicate IsSorted(s:seq<int>)
{
forall i,j :: 0 <= i <= j < |s| ==> s[i] <= s[j]
}

predicate IsPermutation(s1: seq<int>, s2: seq<int>)
{
multiset(s1) == multiset(s2)
}

method insertion_sort(arr: array<int>) modifies arr
ensures IsSorted(arr[..])
ensures IsPermutation(old(arr[..]), arr[..])
{
var index := 0;
while index < arr.Length
invariant index <= arr.Length
invariant IsSorted(arr[..index])
invariant IsPermutation(old(arr[..]), arr[..])
{
var element := arr[index];
var insertion_index := index;
while insertion_index > 0 && arr[insertion_index] < arr[insertion_index - 1]
invariant arr[insertion_index] == element
invariant IsSorted(arr[..insertion_index])
invariant IsSorted(arr[insertion_index..index+1])
invariant forall i,j :: 0 <= i < insertion_index < j <= index ==> arr[i] <= arr[j]
invariant IsPermutation(old(arr[..]), arr[..])
{
arr[insertion_index] := arr[insertion_index - 1];
arr[insertion_index - 1] := element;
insertion_index := insertion_index - 1;
}
index := index + 1;
}
}

method add_four_funny(x: int) returns (y: int)
ensures y == x + 4
{
var z := x + 2;
z := z + 2;
return z;
}

method veryquicksort(arr: array<int>)
modifies arr
ensures IsSorted(arr[..])
{
var index := 0;
while index < arr.Length
invariant index <= arr.Length
invariant forall i :: 0 <= i < index ==> arr[i] <= index
invariant IsSorted(arr[..index])
{
arr[index] := index;
index := index + 1;
}
}
```