Binary Search
《编程之美》中给出的代码(C Language),应该算是一般中规中距的解法。
1 int bisearch(char** arr, int b, int e, char* v)
2 {
3 int minIndex = b, maxIndex = e, midIndex;
4 while(minIndex < maxIndex - 1)
5 {
6 midIndex = minIndex + (maxIndex - minIndex) / 2;
7 if(strcmp(arr[midIndex], v) <= 0)
8 {
9 minIndex = midIndex;
10 }
11 else
12 {
13 maxIndex = midIndex;
14 }
15 }
16 if(!strcmp(arr[maxIndex], v))
17 {
18 return maxIndex;
19 }
20 else if
21 {
22 return minIndex;
23 }
24 else
25 {
26 return -1;
27 }
28 }
2 {
3 int minIndex = b, maxIndex = e, midIndex;
4 while(minIndex < maxIndex - 1)
5 {
6 midIndex = minIndex + (maxIndex - minIndex) / 2;
7 if(strcmp(arr[midIndex], v) <= 0)
8 {
9 minIndex = midIndex;
10 }
11 else
12 {
13 maxIndex = midIndex;
14 }
15 }
16 if(!strcmp(arr[maxIndex], v))
17 {
18 return maxIndex;
19 }
20 else if
21 {
22 return minIndex;
23 }
24 else
25 {
26 return -1;
27 }
28 }
《代码之美》中给出的代码(Java Language)
1 public static int find(String[] keys, String target) {
2 int high = keys.length;
3 int low = -1;
4 while (high - low > 1) {
5 int probe = (low + high) >>> 1;
6 if (keys[probe].compareTo(target) > 0)
7 high = probe;
8 else
9 low = probe;
10 }
11 if (low == -1 || keys[low].compareTo(target) != 0)
12 return -1;
13 else
14 return low;
15 }
2 int high = keys.length;
3 int low = -1;
4 while (high - low > 1) {
5 int probe = (low + high) >>> 1;
6 if (keys[probe].compareTo(target) > 0)
7 high = probe;
8 else
9 low = probe;
10 }
11 if (low == -1 || keys[low].compareTo(target) != 0)
12 return -1;
13 else
14 return low;
15 }
相比而言,后者少了许多边界条件的检查的if-else,这里虽然说的是算法,但是看来语言的功底是万万不能丢的