Binary search condition

3k views Asked by At

I'm always confused about the condition of the binary search algorithm and it costs me a lot of time in programming contests. My question is when to use each of these conditions?
1. while (low < high)
2. while (high - low > 1)
3. while (low <= high)
low = the lowest value in the set of solutions.
high = the largest value in the set of solutions.

1

There are 1 answers

11
John Kurlak On
  1. while (low < high) is used when you're searching the range [low, high). When updating high, use high = mid. When updating low, use low = mid + 1.
  2. while (high - low > 1) is used when you're searching the range (low, high). When updating high, use high = mid. When updating low, use low = mid.
  3. while (low <= high) is used when you're searching the range [low, high]. When updating high, use high = mid - 1. When updating low, use low = mid + 1.

Code below:

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;
    }
}