二分搜索条件

Binary search condition(二分搜索条件)

本文介绍了二分搜索条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我总是对二进制搜索算法的条件感到困惑,它花费了我在编程比赛中的大量时间。我的问题是什么时候使用这些条件?
1.while (low < high)
2.while (high - low > 1)
3.while (low <= high)
low=解决方案集中的最低值。
high=解决方案集中的最大值。

推荐答案

  1. while (low < high)在搜索范围[low, high)时使用。更新high时,请使用high = mid。更新low时,请使用low = mid + 1
  2. while (high - low > 1)在搜索范围(low, high)时使用。更新high时,请使用high = mid。更新low时,请使用low = mid
  3. while (low <= high)在搜索范围[low, high]时使用。更新high时,请使用high = mid - 1。更新low时,请使用low = mid + 1

代码如下:

public class BinarySearch {
    public static void main(String[] args) {
        Integer[] nums = { 4, 9, 12, 18, 20, 26, 28, 29, 55 };

        for (int i = 0; i < nums.length; ++i) {
            System.out.println(binarySearch1(nums, nums[i]));
            System.out.println(binarySearch2(nums, nums[i]));
            System.out.println(binarySearch3(nums, nums[i]));
        }
    }

    public static <T extends Comparable<T>> int binarySearch1(T[] array, T value) {
        final int NOT_FOUND = -1;
        int low = 0;
        int high = array.length;

        while (low < high) {
            int mid = low + (high - low) / 2;
            int comparison = array[mid].compareTo(value);

            if (comparison == 0) {
                return mid;
            } else if (comparison > 0) {
                high = mid;
            } else {
                low = mid + 1;
            }
        }

        return NOT_FOUND;
    }

    public static <T extends Comparable<T>> int binarySearch2(T[] array, T value) {
        final int NOT_FOUND = -1;
        int low = -1;
        int high = array.length;

        while (high - low > 1) {
            int mid = low + (high - low) / 2;
            int comparison = array[mid].compareTo(value);

            if (comparison == 0) {
                return mid;
            } else if (comparison > 0) {
                high = mid;
            } else {
                low = mid;
            }
        }

        return NOT_FOUND;
    }

    public static <T extends Comparable<T>> int binarySearch3(T[] array, T value) {
        final int NOT_FOUND = -1;
        int low = 0;
        int high = array.length - 1;

        while (low <= high) {
            int mid = low + (high - low) / 2;
            int comparison = array[mid].compareTo(value);

            if (comparison == 0) {
                return mid;
            } else if (comparison > 0) {
                high = mid - 1;
            } else {
                low = mid + 1;
            }
        }

        return NOT_FOUND;
    }
}

这篇关于二分搜索条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:二分搜索条件

下一篇: Codness钉板

基础教程推荐