二分查找
前提:有序
思路:
mid = (left + right) / 2
若 mid = value , 输出 mid 下标
若 mid < value , mid = left + 1
若 mid > value , mid = right - 1
public class Test2 {
@Test
public void test1() {
int[] arr = {-99,-54,-2,0,0,2,33,43,256,999};
int left = 0;
int right = arr.length - 1;
int value = -99;
//value 对应的索引
int index = -1;
while (left <= right) {
int mid = (left + right) / 2;
if (value == arr[mid]){
index = mid;
break;
} else if (value < arr[mid]) {
right = mid - 1;
}else if (value > arr[mid]) {
left = mid + 1;
}
}
if (index == -1){
System.out.println("没有");
}else {
System.out.println("索引为:" + index);
}
}
}
标签:二分,arr,right,int,mid,value,查找,left
From: https://www.cnblogs.com/9fall/p/17595308.html