算法: 二分查找,求给定一个 n 个元素有序的(升序)元素不重复的整型数组 和一个目标值 ,写一个函数搜索数组中的 目标值,如果目标值存在返回下标,否则返回 -1。
思路分析:
1.以查找[1,2,3,4,5,6,7,8,9]中的8为例,数组记为nums
2.首先从索引nums[0]-nums[8]的区间即[1,9]中找这个8,发现8可能在数组内
2.先拿数组中间的值nums[4]=5跟8比较,5<8,我们舍掉数组中索引<=4的部分,那么8就存在于索引[4+1,8]的区间
3.然后我们就在nums[5]-nums[8]即6-9中找8这个数,这个区间的中间数为nums[6]=7,7<8,我们舍掉数组中索引<=7的部分,那么8就存在于索引[7+1,8]的区间
4.继续比较,区间确定在了[8,8]到达循环中止条件,发现nums[8]=8,输出索引8,否则输出-1,查询结束
代码如下:
public static int search(int[] nums, int target) {
if (nums.length == 0 || nums[nums.length - 1] < target || target < nums[0]) return -1;
int len = nums.length;
int minIndex = 0;
int maxIndex = len - 1;
while (maxIndex >= minIndex) {
//确定中间索引
int midIndex = (minIndex + maxIndex) / 2;
int midValue = nums[midIndex];
if (midValue > target) {//取小区间
maxIndex = midIndex - 1;
} else if (midValue < target) {//取大区间
minIndex = midIndex + 1;
} else if (nums[midIndex] == target) {
return midIndex;
}
}
return -1;
}
}
测试如下:
public static void main(String[] args) {
int[] nums = {1, 2, 3, 4, 5, 7, 8, 9, 10};
System.out.println("查询结果: "+search(nums, 6));
System.out.println("查询结果: "+search(nums, 7));
}
输出:
查询结果: -1
查询结果: 5