# CSE 227: Lecture 6

The topics covered in this lecture are
Proofs of correctness and an
assignment.
Integer modexp(Integer x, Integer e, Integer n)
{
Integer y = 1, z = x;
while (e > 0) {
if (e odd)
y = y * z mod n;
e = e/2;
z = z * z mod n;
}
return y;
}

loop invariant: `y*z`^{e} = x_{0}^{e0} mod
n.
Assignment: prove the following code correct.
bsort(int data[], int n) {
int i,j;
for (i = n; --i > 0; ) {
for (j = 0; j < i; j++) {
if (data[j] < data[j+1]) {
swap(data,j,j+1);
}
}
}
}

it is probably easier to rewrite this as:
bsort(int data[], int n) {
int i,j;
i = n-1;
// A
while (i > 0) {
// B
j = 0;
// C
while (j < i) {
// D
if (data[j] < data[j+1]) {
swap(data,j,j+1);
}
j++;
// E
}
--i;
// F
}
}

Hints:
`data[i:n-1]` is the sorted partition; `data[0:i-1]` is
not yet sorted. All elements in `data[0:j]` are greater or
equal to `data[j]`. Express this mathematically and show
invariants hold before the loop is entered (base case), and assuming
that the invariants hold after the test but before the body has
executed, show that the invariants will hold after the body is
exectued once (induction step).
To prove that `bsort` works correctly, we also must show that
the contents of `d` did not get trashed, e.g., all elements
replaced with 0. That is, after all, a sorted array. How do we do
this?

Due Tues Feb 4, before class.

## Additional Info

Staniford, Paxson, Weaver:
How to 0wn the
Internet in your spare time

[
search CSE |
CSE |
bsy's home page |
links |
webster |
MRQE |
google |
yahoo |
citeseer |
pgp certserver |
openpgp certserver
]

bsy+cse227w03@cs.ucsd.edu, last updated Wed Jan 29 22:52:08 PST 2003. Copyright 2003 Bennet Yee.

email bsy.