Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading