Professional Documents
Culture Documents
Cse 331 HW 2 1
Cse 331 HW 2 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 = xpre && y = ypre && xpre >= 0 && ypre >=0}
int expt(int x, int y) {
int z = 1;
{inv: xpreypre = xy * z}
while (b: y != 0) {
{inv && b}
if (y % 2 == 0) {
{inv && b && y % 2 = 0}
y = y/2;
{b && (xpreypre = x2y * z)}
x = x*x;
{inv && b}
} else {
{b && inv && y % 2 != 0}
z = z*x;
{b && (xpreypre = xy - 1 * z) && y % 2 != 0}
y = y-1;
{inv}
}
}
{inv && !b} -> {xpreypre = x0 * z = z}
return z;
}
{post: z = xpreypre}
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. {inv1: a[0...j-1] is sorted lowest to highest}
Init: j = 0;
while(b1 : j != n){
{inv1 &&
b1}
init: i = j + 1;
min = j;
{inv1 && b1 && inv2: min = index of smallest value in a[j...i-1]}
while(b2: i < n){
{inv1 && b1 && inv2 && b2}
if(a[i] < min){
(inv1 && b1&& inv2 && b2 && a[i] < min}
min = i;
{inv1 && b1&& min = index of smallest value in a[j...i] && b2}
}
i++;
{inv1 && b1 && inv2}
}
{inv1 && b1 && inv2 && !b2}
swap(a[j], a[i]):
{a[0...j] is sorted}
j++;
{inv1}
}
{inv1 && !b1} → {post: a[0...n-1] is sorted lowest to highest}