标签:bin turn search 二分 amp arc nbsp 有序 key
今年是大年初四,晚上闲的没事儿干,在手机上随手写了二分查找法,对有序数组或者循环有序数组都挺管用!
public int binarySearch(int []nums,int key){
return binarySearch(nums,key,0,nums.length);
}
public int binarySearch(int []nums,int key,int left,int right){
int mid = (left + right) / 2;
if(left <= right){
if(nums[mid] == key){
return mid;
}
if(nums[left] <= nums[mid]){
if(key >= nums[left] && key < nums[mid]){
return binarySearch(nums,key,left,mid - 1);
} else {
return binarySearch(nums,key,mid + 1,right);
}
} else {
if(key > nums[mid] && key <= nums[right]){
return binarySearch(nums,key,mid + 1,right);
} else {
return binarySearch(nums,key,left,mid - 1);
}
}
} else
return -1;
}
}
标签:bin turn search 二分 amp arc nbsp 有序 key
原文地址:http://www.cnblogs.com/txq157/p/6359083.html