二分法查找的关键是根据数组中间索引进行不断的二分来实现对数据的查找,注意此处数组必须为有序数组,示例代码如下:
- public class BinarySearch {
- /**
- 在二分法查找中,从数列的中间开始搜寻,如果这个数小于我们所搜寻的数,由于数列已排序,则该数左边的数一定都小于要搜寻的对象,所以无需浪费时间在左边的数;如果搜寻的数大于所搜寻的对象,则右边的数无需再搜寻,直接搜寻左边的数。
- */
- public static int search(int[] nums, int num) {
- int minIndex = 0;
- int maxInde = nums.length - 1;
- while (minIndex <= maxIndex) {
- int midIndex = (minIndex + maxIndex) / 2;
- //与中间值比较确定在左边还是右边区间,以调整区域
- if (num > nums[midIndex]) {
- minIndex = midIndex + 1;
- } else if (num < nums[midIndex]) {
- maxIndex = midIndex - 1;
- } else {
- return midIndex;
- }
- }
- return -1;
- }
- //二分查找的实现
- public static void main(String[] args) {
- int[] nums = { 2,4,5,6,9,11,13,15,19,20,22, 91};
- int find = BinarySearch.search(nums,5);
- if (find != -1) {
- System.out.println("找到数值于索引" + find);
- } else {
- System.out.println("找不到数值");
- }
- }
- }