1.实现
二分查找算法要求数组必须是有序的。
把中间的值和要查询的值进行比较,相等则返回索引下标
arr[middle]>number
,则让尾索引等于middle-1,
arr[middle]<number
,则让开始索引等于middle+1。
int[] arr = new int[]{-99,-54,-2,0,2,33,43,256,999};
boolean isFlag = false;
int number = 256;
int start = 0; //开始索引
int end = arr.length-1; //尾索引
while (start<=end){
int middle = (start+end)/2;
if (arr[middle]==number){
System.out.println("找到指定的元素,索引为:"+middle);
isFlag = true;
break;
}else if (arr[middle]>number){
end = middle -1;
}else {
start = middle+1;
}
}
if (!isFlag){
System.out.println("未找到指定的元素");
}
标签:二分,arr,Java,索引,int,middle,算法
From: https://www.cnblogs.com/zhishu/p/16616537.html