package day8;
//二分查找 1.数组元素必须是有序的
public class lianxi2
{
public static void main(String[] args)
{
int[] arr = {1,2,4,6,7,8};
//要查找的数
int value = 4;
int index = -1;
int left = 0;
int right = arr.length-1;
int mid = (left + right)/2;
while(left <= right)
{
//找到了
if(arr[mid] == value)
{
index = mid;
break;
}
else if(arr[mid] > value)
{
left = mid + 1;
}
else if(arr[mid] < value)
{
right = mid - 1;
}
mid = (left + right)/2;
}
if(index == -1)
System.out.println(value + "不存在");
else
System.out.println(value + "在数组的下标是:" + index);
}
}
21.二分查找
最新推荐文章于 2021-06-11 20:37:55 发布