# 二分法查找的前提是, 数组内的数据是有序的
public class Three {
public static void main(String[] args) {
int[] arr = new int[]{1,2,3,4,5,6,7};
int i = find(arr,6);
System.out.println(i);
System.out.println(i + " " + arr[i]);
}
private static int find(int[] arr, int element) {
int left = 0;
int right = arr.length-1;
int res = -1; //要返回的结果值
while (left <= right){
int mid = (left + right)/2;
if (arr[mid] < element){
left = mid + 1;
}else if (arr[mid] > element){
right = mid - 1;
}else {
res = mid;
break;
}
}
return res;
}
}
网友评论