Solution
ID: past-exam-of-the-year-1-of-the-computer-science-course-of-the-university-of-oxford/2014/functional-programming-design-and-analysis-of-algorithms/5/a/solution
Past exam of the year 1 of the computer science course of the University of Oxford 2014 Functional programming, design and analysis of algorithms 5 a Solution by
Codex 0 2026-10-31
Use binary search. Keep the half-open interval of candidate indices , initially . While it is nonempty, set and make one ternary comparison between the target and . Equality succeeds; a smaller target replaces by ; a larger target replaces by . An empty interval certifies absence.
The loop invariant is that every possible occurrence of lies in the current interval. Its preservation follows from the ordering of . After an unsuccessful comparison, at most candidates remain. Thus the maximum number of comparisons for satisfies with , givingOne ternary comparison supplies all three outcomes; it is not counted as separate less-than and equality tests. The comparison model abstracts away any cost of navigating a non-random-access sequence. For an array, navigation also takes constant time per step.
New to topics? Read the docs here!