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*ze = x0e0 mod n.
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.
bsy+cse227w03@cs.ucsd.edu, last updated
email bsy.