二分查找法
int binarySearch(int a[],int n,int key) {
int low = 0,mid,high = n - 1;
while(low <= high) {
mid = (low + high)/2;
printf("mid=%d\n",mid);
if (key < a[mid]) {
high = mid - 1;
} else if (key > a[mid]) {
low = mid +1;
} else {
return mid;
}
}
return -1;
}
二分查找法(递归)
int binarySearch(int a[],int n,int low,int high,int key) {
int low = 0,mid,high = n - 1;
if(low <= high) {
mid = (low + high)/2;
printf("mid=%d\n",mid);
if (key < a[mid]) {
return binarySearch(a,n,low,mid-1,key);
} else if (key > a[mid]) {
return binarySearch(a,n,mid+1,high,key);
} else {
return mid;
}
}
return -1;
}