forked from Hawstein/cracking-the-coding-interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path9.5.cpp
More file actions
25 lines (24 loc) · 643 Bytes
/
9.5.cpp
File metadata and controls
25 lines (24 loc) · 643 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
using namespace std;
int search(string s[], int low, int high, string x){
if(x == "") return -1;
while(low <= high){
int mid = (low+high)>>1;
int t = mid;
while(s[t] == "" && t <= high) ++t;
if(t > high) high = mid - 1;
else{
if(s[t] == x) return t;
else if(s[t] < x) low = t + 1;
else high = mid - 1; //or t-1, (mid, t)为空字符串
}
}
return -1;
}
int main(){
string s[13] = {
"at", "", "", "", "ball", "", "", "car", "", "", "dad", "", ""
};
cout<<search(s, 0, 12, "ball")<<endl;
return 0;
}