首页 > 代码库 > 二分查找

二分查找

二分查找的前提是数组是有序的,这点我们要注意,我们可以在使用二分查找的时候先对数组进行排序。下面附上代码。

class Demo14_1{
	public static void main(String[] args) throws IOException{
		int[] arr ={0,1,2,3,4,5};
		int a = find(arr,-1);
		System.out.println(a);
		
	}
	public static int find(int[] arr,int number){
		if(arr == null && arr.length ==0) return -1;
		if(arr.length == 1 && arr[0] == number ) return 0;
		
		int min = 0;
		int max = arr.length -1;
		int mid = max/2;
		while(true){
			if(number > arr[mid]){
				min = mid+1;
				mid = (max+min)/2;
			}else if(number < arr[mid]){
				max = mid-1;
				mid = (max+min)/2;
			}else{
				return mid;
			}
			if(max<min){
				return -1;
			}
		}
	}
}

  

二分查找