二分查找O(logn)


//二分查找O(logn),要求arr為有序數組
	public static int 二分查找(int[] arr,int target){
		int start = 0;
		int end = arr.length-1;
		while(start<=end){
			int mid = (start+end)/2;
			if(arr[mid] > target){
				end = mid-1;
			}else if(arr[mid] < target){
				start = mid+1;
			}else{
				return mid;
			}
		}
		return -1;
	}
 
//遞歸實現
 
public static int 二分查找(int[] arr,int target,int start,int end){
		if(start <= end){
			int mid = (start+end)/2;
			if(arr[mid] > target){
				end = mid-1;
			}else if(arr[mid] < target){
				start = mid+1;
			}else{
				return mid;
			}
			return 二分查找(arr,target,start,end);
		}
		return -1;
	}


 


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2021 ITdaan.com