1 /************************************************************
2 function: 找出一个有序数组(字典序)字符数组arr中值等于字符串v的元素的序号,
3 如果有多个元素满足这个条件,则返回其中序号最大的
4
5 author: hahali
6 time: 2011年6月12日21:47:40
7 *************************************************************/
8
9
10 #include <iostream>
11 using namespace std;
12
13 int bisearch(char **arr, int b, int e, char *v)
14 {
15 int minIndex = b, maxIndex = e, midIndex = 0;
16 //循环结束有两种情况:
17 //若minIndex 为偶数则minIndex == maxIndex;
18 //否则minIndex == maxIndex - 1;
19 while (minIndex < maxIndex - 1)
20 {
21 midIndex = minIndex + ((maxIndex -minIndex) >> 1);
22
23 if(strcmp(arr[midIndex], v) <= 0)
24 {
25 minIndex = midIndex;
26 }
27 else
28 {
29 //防止minIndex == maxIndex,不要minIndex - 1
30 maxIndex = midIndex;
31 }
32 }
33 if (!strcmp(arr[maxIndex], v))
34 {
35 return maxIndex;
36 }
37 else if(!strcmp(arr[minIndex], v))
38 {
39 return minIndex;
40 }
41 else
42 {
43 return -1;
44 }
45 }
46
47 int main()
48 {
49 char *a[] = {"hello", "yello", "zebra"};
50 char v[10] = "zebra";
51 cout << bisearch((char**)a, 0, 2, v) << endl;
52
53 return 0;
54 }