1.迭代法
public static int rank(int key,int nums[]){
int low = 0;
int high = nums.length - 1;
int notFind = -1;
while(low <= high){
int middle = (high + low) / 2;
if(nums[middle] > key){
high = middle - 1;
}else if(nums[middle] < key){
low = middle + 1;
}else{
return middle;
}
}
return notFind;
}
2.递归法
public static int search(int num,int low,int high,int a[]){
int middle = (high + low) / 2;
while(low <= high){
if(a[middle] > num){
return search (num,low ,middle - 1,a);
}else if(a[middle] < num) {
return search(num,middle + 1,high,a);
}else{
return middle;
}
}
return -1;
}
网友评论