Note that the postcondition on the first problem is amended to include the precondition (and in the precondition the names of some bound variables are changed to avoid confusion with program variables - technically there is no ambiguity between i,j as bound variables in Q and program variables i,j. but we humans may inadvertently confuse bound and unbound instances.)
and the goal is to compute with indices i and j until they reach the first
double dipper.
With that background we may write the postcondition simply as
<
{R: (i = iv) ^ (j = jv) ^ Q}
Design a loop with invariant and bound to meet this specification.
{Q} i,j := 0,0; {inv P: ??} {bound t: ??} do ?? od {R}
Each of the following programs purports to be do partitioning (as in quicksort) of a given array of integers b[0:n-1] with respect to a given value x. Each contains one or more bugs, Give a state (a specific array b and an x) satisfying the initial precondition, but for which, after program execution, the postcondition fails to hold. Explain which of the 5 checklist points fails to hold (any one of them, if more than one fail). If your original answer does the job, just return it. If it does the job but contains extra info such as proofs of checkpoint items that do hold, clearly mark the essential part: the counterexample state and it's explanation.
// program A: partition given array b[0:n-1] with respect to value x. {Q: (E i: 0 ≤ i < n: b[i] = x} i,j:= 0, n-1; {inv P: (A k: 0 ≤ k < i: b[k] ≤ x) ^ (A k: j < k ≤ n: b[k] ≥ x) {bound t: j - i} do b[i] &le x → i := i+1 [] b[j] &ge x → j := j-1 [] b[j] ≤ x ^ x ≤ b[i] → i,j,b[i],b[j] := i+1, j-1, b[j],b[i] od {R: (A k: 0 ≤ k ≤ i: b[k] ≤ x) ^ (A k: i < k < n: b[k] ≥ x)
// program B: partition given array b[0:n-1] with respect to value x. {Q: (E i: 0 ≤ i < n: b[i] = x} i,j:= 0, n-1; {inv P: (A k: 0 ≤ k < i: b[k] ≤ x) ^ (A k: j < k ≤ n: b[k] ≥ x) {bound t: j - i} do i < j ^ b[i] &le x → i := i+1 [] i ≤ j ^ b[j] &ge x → j := j-1 [] b[j] ≤ x ^ x ≤ b[i] → i,j,b[i],b[j] := i+1, j-1, b[j],b[i] od {R: (A k: 0 ≤ k ≤ i: b[k] ≤ x) ^ (A k: i < k < n: b[k] ≥ x)
// program C: partition given array b[0:n-1] with respect to value x. {Q: T} i,j:= -1, n-1; {inv P: (A k: 0 ≤ k ≤ i: b[k] ≤ x) ^ (A k: j < k ≤ n: b[k] ≥ x) {bound t: j - i} do i < j ^ b[i+1] &le x → i := i+1 [] i < j ^ b[j] &ge x → j := j-1 [] b[j] ≤ x ^ x ≤ b[i+1] → i,j,b[i+1],b[j] := i+1, j-1, b[j],b[i+1] od {R: (A k: 0 ≤ k ≤ i: b[k] ≤ x) ^ (A k: i < k < n: b[k] ≥ x)