Search code examples
javaalgorithmbinary-search

Binary Search implementation via java


Please see the below java source code for binary search implementation

public class Main {
    public static void main(String[] args) {

        int[] x = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
        int y = binarySearch(x, 11);
        System.out.println(y);

    }

    public static int binarySearch(int[] arr, int value) {
        int searchedIndex = -1;
        int first = 0;
        int last = arr.length - 1;
        int mid;

        while (first <= last) {
            mid = (first + last) / 2;

            if (arr[mid] == value) {
                searchedIndex = mid;
                break;
            } else {
                if (value < arr[mid]) {
                    last = mid - 1;
                } else {
                    first = mid + 1;
                }
            }
        }

        return searchedIndex;
    }
}

int last = arr.length - 1 is -1 compulsory or not. I feel that code works fine either last = arr.length - 1. If its compulsory please explain why.


Solution

  • The -1 is needed for one very specific case: when you search for a value that is larger than the largest value in the array. For example, calling your function with

    int y = binarySearch(x, 50);
    

    will throw an ArrayOutOfBounds exception. That's because mid will eventually be equal to last, and without the -1, last is past the end of the array.