Solution

ID: past-exam-of-the-year-1-of-the-computer-science-course-of-the-university-of-oxford/2015/imperative-programming-resit/2/b/solution

Use binary search on an interval with unequal endpoint values. The array need not be sorted:
l := 0; r := n;
WHILE r-l > 1 DO
  m := l + (r-l) DIV 2;
  IF b[l] # b[m] THEN r := m ELSE l := m END
END;
k := l;
The loop invariant is
It holds initially by the given endpoint inequality, which also implies . When , . If , replacing maintains unequal endpoints. Otherwise , so replacing maintains them. This does not require monotonicity or even just two possible values.
The positive integer width is a loop variant, reduced to at most its old half rounded up. On exit , giving
There are at most iterations. The additive constant handles .

New to topics? Read the docs here!