You are on page 1of 4

1.

{pre: size > 0}


init: k = 0, max = items[0]
{inv: max = largest in items [0...k]}
while(b: k+1 != size){
{inv && b}
if(items[k + 1] > max){
{inv && b && items[k+1] > max}
max = items[k+1];
{b && max = largest in items [0…k+1]}
} else{
{b && max = largest in items[0...k+1]}
}
{b && max = largest in items[0...k+1]}
k++;
{max = largest in items[0...k]} -> {inv}
}
{inv && !b} -> {post: max largest in items[0… size-1]}

Adjusting the invariant by 1 meant that we also had to adjust the loop body, b, and the
initialization. Changing k - 1 to k in the invariant meant we had to change the if condition from k
to k + 1, b from k != size to k + 1 != size, the assertions at the end of the loop, and the
initialization from k = 0 to k = 1. There was a ripple effect of having to adjust everything else by
1, but it was still relatively simple to follow the process described in class to change everything.
2. {pre: x = x​pre​ && y = y​pre && ​ x​pre​ >= 0 && y​pre >=0}

int expt(int x, int y) {
int z = 1;
{inv: x​pre​ypre​ = x​y​ * z}
while (​b​: y != 0) {
{inv && b}
if (y % 2 == 0) {
{inv && b && y % 2 = 0}
y = y/2;
{b && (x​pre​ypre​ = x​2y​ * z)}
x = x*x;
{inv && b}
} else {
{b && inv && y % 2 != 0}
z = z*x;
{b && (x​pre​ypre​ = x​y - 1​ * z) && y % 2 != 0}
y = y-1;
{inv}
}
}
{inv && !b} -> {x​pre​ypre​ = x​0 ​* z = z}
return z;
}
{post: z = x​pre​ypre​}
3. {pre: n >= 2}
{inv: a[0...j-1] <= a[0]​pre​ && a [k...n-1] > a[0]​pre​}
Init: j = 1;
Init: k = n-1;
while{​b​: k - j != 1}
{inv && b}
if(a[j] <= a[0]​pre​){
{inv && b && a[j] <= a[0]​pre​}
swap(a[0]​pre​, a[j])
{a[0...j] <= a[0]​pre​ && a[k...n-1] > a[0]​pre​}
j++;
{inv}
} else {
{inv && b && a[j] > a[0]​pre​}
swap(a[j], a[k]);
{a[0...j-1] <= a[0]​pre​ && a[k - 1… n-1] > a[0]​pre​}
k--;
{inv}
}
}
{inv && !b} -> {post: a[0… j-1] <= a[0]​pre​ && a[k...n-1] > a[0]​pre​ && j - k = 1 && a[j] = a[0]​pre​}
4. {inv​1​: a[0...j-1] is sorted lowest to highest}
Init: j = 0;
while(​b1​​ : j != n){
{inv​1 &&
​ b​1​}
init: i = j + 1;
min = j;
{inv​1 ​&& b​1​ && inv​2​: min = index of smallest value in a[j...i-1]}
while(​b​2​: i < n){
{inv​1​ && b​1​ && inv​2​ && b​2​}
if(a[i] < min){
(inv​1​ && b​1​&& inv​2​ && b​2​ && a[i] < min}
min = i;
{inv​1​ && b​1​&& min = index of smallest value in a[j...i] && b​2​}
}
i++;
{inv​1​ && b​1​ && inv​2​}
}
{inv​1​ && b​1​ && inv​2​ && !b​2​}
swap(a[j], a[i]):
{a[0...j] is sorted}
j++;
{inv​1​}
}
{inv​1​ && !b​1​} → {post: a[0...n-1] is sorted lowest to highest}

You might also like