public static void main(String[] args) {
int[] a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// int target = 11;
int target = 4;
int left = 0;
int right = a.length-1;
while (left <= right) {
int middle = (left + right) / 2;
if (a[middle] > target) {
right = middle-1;
}else if(a[middle]<target){
left = middle+1;
}else {
System.out.println("target index is :"+middle);
System.exit(0);
}
}
System.out.println(-1);
}
注意:数组必须是有序的!