public class binarySearch {
public static void main(String[] args) {
//寻找指定元素的下标
//二分查找前提是被查找对象必须有序
int[] arr = {1,2,3,4,5,6,7,8,9,10};
int index = binarySearchh(arr,9);
System.out.println(index == -1 ? "该元素不存在!" : "该元素下标为" + index);
}
private static int binarySearchh(int[] arr, int i) {
int begin = 0;
int end = arr.length - 1;
while(begin <= end){//循环就可以了,不要用递归,递归效率太低。
int mid = (begin + end) / 2;//找到中间元素
if (arr[mid] == i) {
return mid;
}
else if (arr[mid] < i) {//目标在中间元素右边
begin = mid + 1;
}
else {//目标在中间元素左边
end = mid - 1;
}
}
return -1;
}
}