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…
Related articles
Related CZ Podcast episodes
- #3 · Java 6 SE, Vývoj webových aplikací
Dagi and Filemon discuss Java 6 and web application frameworks. · Czech audio
- #1 · Vývojová prostředí v Javě
The first CZ Podcast episode looks at Java development environments. · Czech audio