java-二分法查找

时间:2021-06-01 22:09:16

1.二分法查找数字在数组中的索引位置

2.注意数组特别大,两个数字相加越界问题

public class BinarySearch {
	
	public static void main(String[] args) {
		Integer[] dataArr = {1,2,3,4,5,6,7,8,9};
		/**
		 * 若区间[start,end],那么传入start,end
		 * 	 区间[start,end),那么传入start,end-1
		 * 	 区间(start,end),那么传入start+1,end-1
		 * */
		int a = binarySearch(dataArr, 0, 8, 9);
		System.out.println(a);
	}
	public static Integer binarySearch(Integer[] arr, int left, int right, Integer data) {
		int l = left, r = right, mid = 0;
		if(left <= right
				|| left >= 0
				|| right < arr.length) {
			while(l <= r) {
				//这里判断以下整形特别大累加越界
				mid = l + (r - l)/2;
				if(arr[mid] == data) {
					return mid;
				}
				if(data > arr[mid]) {
					l = mid + 1;
				} else {
					r = mid;
				}
			}
		}
		return -1;
	}
}