Pulsars
0 %
Log inSign up

Implementing and avoiding the pitfalls

The classic pitfalls

Three mistakes come up constantly when writing a binary search. Knowing them will let you spot them immediately in your own code or in a classmate's.

First pitfall: applying binary search to an UNSORTED array. The algorithm never checks that the array is sorted, it just trusts that order to eliminate a half. On [8, 2, 19, 4, 11], searching for 4 can fail even though 4 is indeed present, because the comparison with the middle does not reflect the target's real position.

unsorted array: [8, 2, 19, 4, 11], target = 4
middle (index 2) = 19  ->  19 > 4  -> eliminate the RIGHT half (indices 3 and 4)
but 4 is exactly at index 3, in the eliminated part!
incorrect result: target not found even though it exists

Second pitfall: miscomputing the middle index, especially with an even number of elements. (gauche + droite) // 2 always rounds down in Python: on the interval [4, 5], the middle is 4, not 5. This choice must be consistent with the way you then tighten the bounds, otherwise you risk an infinite loop where left and right no longer move.

Third pitfall: forgetting to handle the empty array or the absent target. If len(a) == 0, then droite = -1 from the start and the loop while gauche <= droite never runs: this is in fact the correct behaviour, provided the function does return -1 (or a value clearly signalling « not found ») after the loop, and not an error or a random index.

empty array: a = [], target = 5
gauche = 0, droite = -1  ->  gauche > droite  ->  loop not run  ->  return -1 (correct)

In summary: always check that your array is sorted before using binary search, test your bounds on edge cases (empty array, single element, target at the ends), and keep a stopping condition consistent between the middle computation and the update of left/right.