对于排序这点事,好久不想,乍然想起有点伤脑经.今天手写一下二分查找.注意这个排序的前提:数据已经提前排好序了!!!不然无法使用.对于优化条件,我也就想到这些了,有啥建议留言吧.
/**
* 二分查找:前提=数据为有序的。
*
*/
public class BinarySearch {
//递归方式
public static int binarySearchRecursion(int[] arr,int num,int low, int high){
//不能使用low=high,否则有些情况出错。例:low=1,high=2,而此时high位置上的数=num,如递归条件为low>=high,结果出错!!!
//对于arr[low]>num || arr[high] <num,对于num小于arr[0]或大于arr[arr.length-1]的情况,可以快速返回结果。
if(low>high || arr[low]>num || arr[high] <num) return -1;
int mid = (low+high)/2;
if(arr[mid] == num) return mid;
else if(arr[mid] < num ) return binarySearchRecursion(arr,num,mid+1,high);//mid+1必须如此,不然当low=high-1时,low=mid,如num所在的目标索引在high位置,则陷入死循环.
else return binarySearchRecursion(arr,num,low,mid-1);//这里low=mid是可以的.
}
public static void main(String[] args) {
int[] arr = {1,4,5,6,7,12};
int index = binarySearchRecursion(arr,12,0,arr.length-1);
System.out.println("索引" + index);
}
}
Java 二分查找
最新推荐文章于 2023-09-12 08:06:23 发布