java实现二分查找及其变种

普通二分查找(查找等于指定值的索引下标)

非递归实现

public class Client {

  public static void main(String[] args) {
    int[] nums = {1, 3, 5, 7, 9, 10};
    System.out.println(binarySearch(nums, 5));
  }

  private static int binarySearch(int[] nums, int target) {
    int left = 0;
    int right = nums.length - 1;
    //在区间[left,right]中查找target
    while (left <= right) {
      int middle = left + ((right - left) >> 1);
      if (nums[middle] > target) {
        right = middle - 1;
      } else if (nums[middle] < target) {
        left = middle + 1;
      } else {
        return middle;
      }
    }
    return -1;
  }
}

递归实现

public class Client2 {

  public static void main(String[] args) {
    int[] nums = {1, 3, 5, 7, 9, 10};
    System.out.println(binarySearch(nums, 10));
  }

  private static int binarySearch(int[] nums, int target) {
    return binarySearch(nums, 0, nums.length - 1, target);
  }

  private static int binarySearch(int[] nums, int left, int right, int target) {
    //在区间[left,right]中查找target
    if (left > right) {
      return -1;
    }
    int middle = left + ((right - left) >> 1);
    if (nums[middle] > target) {
      return binarySearch(nums, left, middle - 1, target);
    }
    if (nums[middle] < target) {
      return binarySearch(nums, middle + 1, right, target);
    }
    return middle;
  }
}

查找大于指定值的最小索引下标

public class Client3 {

  public static void main(String[] args) {
    int[] nums = {1, 1, 3, 3, 5, 5};
    for (int i = 0; i <= 6; i++) {
      System.out.println(binarySearch(nums, i));
    }
  }

  /**
   * 查找大于target的最小索引
   */
  private static int binarySearch(int[] nums, int target) {
    int left = 0;
    int right = nums.length;
    //在区间[left,right]中查找大于target的最小索引,找不到的话right=nums.length
    while (left < right) {
      int middle = left + ((right - left) >> 1);
      if (nums[middle] > target) {
        //middle可能是大于target的最小值,也可能不是,所以右区间要包含middle
        right = middle;
      } else {
        left = middle + 1;
      }
    }
    return right == nums.length ? -1 : right;
  }
}

查找小于指定值的最大索引下标

public class Client4 {

  public static void main(String[] args) {
    int[] nums = {1, 1, 3, 3, 5, 5};
    for (int i = 0; i <= 6; i++) {
      System.out.println(binarySearch(nums, i));
    }
  }

  /**
   * 查找小于target的最大索引
   */
  private static int binarySearch(int[] nums, int target) {
    int left = -1;
    int right = nums.length - 1;
    //在区间[left,right]中查找小于target的最大索引,找不到的话left=-1
    while (left < right) {
      //求中间值向上取整 [1,2]取2,默认是向下取整的
      int middle = left + ((right - left + 1) >> 1);
      if (nums[middle] < target) {
        left = middle;
      } else {
        right = middle - 1;
      }
    }
    return left;
  }
}

这个二分查找变种和上一种类似,但是有一个坑,就是当left和right相邻的时候,会死循环,这是因为默认求中位数是向下取整的,如数组[1,2],向下取整取1,向上取整取2。

上一篇:[国家集训队]middle


下一篇:css 常用属性收集(持续更新 )