//使用折半查找来查找一个数
//arr是数组
//len是数组长度
//key是要查找的数(关键字)
//return 返回要查找的数的位置,如果查找不到,返回 -1
int searchItem(int arr[],int len,int key){
int low=0,high=len-1,mid;
while(low<=high){
mid=(low+high)/2;
if(key>arr[mid]){
low=mid+1;
}else if(key<arr[mid]){
high=mid-1;
}else{
return mid;
}
}
//如果查找不到,返回-1
return -1;
}
int main(){
int arr[]={3,4,12,20,21,23,28,45,67,100};
//查找key值=20
int loc=searchItem(arr,10,20);
printf("loc = %d\n",loc);
}
|
|