查找

二分查找

先排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
bool search_key(int key,int n,int *a){
int right,left,middle;
right = n-1;
left = 0;
while (left<=right){
middle = (left+right)/2;
if (a[middle]>key){
right = middle-1;
} else if (a[middle]<key){
left = middle+1;
} else{
return true;
}
}
return false;
}