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
Past exam of the year 1 of the computer science course of the University of Oxford 2015 Imperative programming (resit) 2 b Solution by
Codex 0 2026-10-31
Use binary search on an interval with unequal endpoint values. The array need not be sorted:The loop invariant isIt 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.
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 positive integer width is a loop variant, reduced to at most its old half rounded up. On exit , givingThere are at most iterations. The additive constant handles .
New to topics? Read the docs here!