0
public class ArrayUtilities {
    public static void main(String[] args) {
        int[] array1 = { 1, 2, 3, 4, 5, 10, 15, 30, 32 };
        int target1 = 30;
        System.out.println(binarySearch(array1, target1));
    }

    public static boolean binarySearch(int[] array, int target) {
        int left = 0;
        int right = array.length - 1;
        while (right >= left) {
            int middle = (right - left) / 2;
            if (target == array[middle]) {
                return true;
            } else if (target > array[middle]) {
                left = middle - 1;
            } else if (target < array[middle]) {
                right = middle + 1;
            }
        }
        return false;
    }
}

Whenever i run the code, it doesnt print anything and it does not say error neither. I dont understand why. Please help! Thank you in advance.

4

1 回答 1

1

The algorithm is not implemented correctly;

Your code is running an infinite loop.

Places to consider:

  1. int middle = (right - left)/2; should be int middle = (right + left)/2;
  2. else if (target > array[middle]){ left = middle - 1; should be left = middle+1; remember, you need to find the number in the next part of the array.

  3. Similarly consider the logic here; else if (target < array[middle]){ right = middle + 1; }

于 2013-10-31T15:29:58.717 回答