Part 17 / Topic 7 of 12
Binary search
Binary search finds a value in O(log n) by repeatedly halving the search range, instead of scanning element by element — but it needs sorted data, full stop. This is the one precondition in this whole part that, when skipped, doesn't crash — it just quietly returns a wrong answer. Think of looking up a name in a phone book: you don't start at "A" and read every name; you open to the middle, see which half the name must be in, and repeat — that only works because the names are already in order.
fun binarySearchSteps(sortedPincodes: IntArray, target: Int): Pair<Int, Int> {
var low = 0
var high = sortedPincodes.size - 1
var steps = 0
while (low <= high) {
steps++
val mid = low + (high - low) / 2 // avoids overflow vs. (low + high) / 2
when {
sortedPincodes[mid] == target -> return steps to mid
sortedPincodes[mid] < target -> low = mid + 1
else -> high = mid - 1
}
}
return steps to -1
}
$ kotlinc BinarySearchDemo.kt -include-runtime -d bs.jar
$ java -jar bs.jar
sorted pincodes: [110001, 122001, 160017, 380001, 411001, 500001, 560001, 600001, 700001, 800001]
-- linear vs binary search for 560001 (near the end) --
linear search:
found in 7 step(s)
binary search:
found in 4 step(s)
index: 6
-- sortedPincodes.binarySearch() on a sorted IntArray --
binarySearch(411001): index 4
binarySearch(999999, not present): -11 (negative: -(insertion point) - 1, here -(10)-1)
-- binarySearch on a sorted List<T>, with a comparator --
station with code 340: Kalyan at index 2
-- the one precondition: unsorted data gives a WRONG, meaningless answer --
unsorted array: [500001, 110001, 700001, 160017]
binarySearch(160017) on unsorted data: -3 (looks like 'not found' but 160017 IS in the array, at index 3 -- sort first, always)
Two stdlib functions cover almost every real case: IntArray.binarySearch(target) for primitive arrays, and List<T>.binarySearch { comparison } for a list with a comparison lambda — both return the index if found, and a negative number encoding the insertion point if not (-(insertion point) - 1, which is why -11 means "would belong at index 10"). The last block is the whole point of this section: 160017 genuinely sits at index 3 of the unsorted array, and binarySearch still reports it missing, because it trusts the "sorted" precondition completely and never checks it for you.
⚠️
binarySearchnever verifies the data is sorted. It is faster because it skips that check. If there's any doubt, sort first (section 6) — the cost of sorting once is almost always smaller than the cost of debugging a search that lies.
Full program: examples/binary-search/BinarySearchDemo.kt.
Done here? The practice set for Part 17 — including the solutions — is on the part page.