dagblog.
← Archive

A programming puzzle


Here's an interesting programming puzzle. Who can spot the bug in the following simple code, which implements a binary search? The array is sorted.

01 public static int binarySearch(int[] a, int key) {

02 int low = 0;

03 int high = a.length - 1;

04 

05 while (low <= high) {

06 int mid = (low + high) / 2;

07 int midVal = a[mid];

08 

09 if (midVal < key)

10 low = mid + 1;

11 else if (midVal > key)

12 high = mid - 1;

13 else

14 return mid; // key found

15 }

16 return -(low + 1); // key not found.

17 }

 
 

Java2html

I freely admit I couldn't figure it out. It isn't that simple. Whoever gets it has my full admiration! I'll just add that this code was part of the Java API for years…

Medium version

Related articles

Related CZ Podcast episodes