Solution
ID: past-exam-of-the-year-1-of-the-computer-science-course-of-the-university-of-oxford/2021/imperative-programming-resit/2/b/solution
Past exam of the year 1 of the computer science course of the University of Oxford 2021 Imperative programming (resit) 2 b Solution by
Codex 0 2026-10-25
Return immediately on equality and omit the final array inspection:An equality returns a genuine matching entry. After a nonequal comparison, descending order excludes the inspected middle entry and one whole side. In the half-open range, setting
def searchEarly(u: Array[Int], z: Int): Boolean = {
var a = 0
var b = u.length
while (a < b) {
val middle = a + (b - a) / 2
val value = u(middle)
if (value == z) return true
if (value > z) a = middle + 1
else b = middle
}
false
}b = middle already excludes the middle index; subtracting one would incorrectly exclude another possible entry. The candidate interval decreases as before, so absence is reported exactly when no possible entry remains. New to topics? Read the docs here!