Lucky #6:
Binary Search may look simple, but a bug on it could live for a decade.
In 2006, Joshua Bloch posted "Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken".
The following is the code he posted:
1: public static int binarySearch(int[] a, int key) {
2: int low = 0;
3: int high = a.length - 1;
4:
5: while (low <= high) {
6: int mid = (low + high) / 2;
7: int midVal = a[mid];
8:
9: 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: }
The bug is in line 6 and it's fixed in Java 6.
Joshua Bloch proposed two approaches,
int mid = low + ((high - low) / 2);
or
int mid = (low + high) >>> 1;
In Java 6's src.zip, I can see the second approach is chosen.
No comments:
Post a Comment