Search code examples
algorithmbinary-search

Binary Search: Program doesn't terminate


I've been trying to learn algorithms and as part of this I have been trying to code binary search and the logic seems fine. The code doesn't terminate and the IDE stays idle forever. I don't understand what I'm doing wrong. Any help is appreciated. Thanks in advance!

public class BinarySearch {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        int no = 5;
        System.out.print(binSearch(arr, no, 0, arr.length - 1));


    }

    private static boolean binSearch(int[] arr, int no, int start, int end) {
        while(start <= end) {
            int mid = (start + end) / 2;
            if (arr[mid] == no) {
                return true;
            } else if (no > arr[mid]) {
                binSearch(arr, no, mid + 1, end);
            } else if(no < arr[mid]) {
                binSearch(arr, no, start, mid - 1);
            }
        }
        return false;
    }
}

Solution

  • You are missing the return on the two recursive calls:

    private static bool binSearch(int[] arr, int no, int start, int end) {
        
        while(start <= end) {
            int mid = (start + end) / 2;
            if (arr[mid] == no) {
                return true;
            } else if (no > arr[mid]) {
                return binSearch(arr, no, mid + 1, end);
            } else if(no < arr[mid]) {
                return binSearch(arr, no, start, mid - 1);
            }
        }
        return false;
    }
    

    You could also consider writing it in a non-recursive loop.