Search code examples
javaalgorithmsortingdata-structuresbinary-search

Why is there still an error case in this binary search of sorted array scenario?


For the record, I came across this question on some web coding site, but I am really interested in what I missed rather than scores. Here it goes:

Implement function countNumbers that accepts a sorted array of unique integers and counts the number of array elements that are less than the parameter lessThan.

For example, SortedSearch.countNumbers(new int[] { 1, 3, 5, 7 }, 4) should return 2 because there are two array elements less than 4.

I give the following solution, however, I just can not figure out in what scenario will it fail? (the site says it fails 1 out of 4 tests). And I also am not sure what kind of assumption I can have for value lessThan.

public class SortedSearch {
    public static int countNumbers(int[] sortedArray, int lessThan) {

        if (sortedArray == null || sortedArray.length == 0)
            return 0;

        if (sortedArray.length == 1) {
            return sortedArray[0] < lessThan? 1:0;
        }

        int left = 0;
        int right = sortedArray.length-1;
        int middle = 0;

        while(left<right) {
            middle = left + (right-left)/2;
            if (sortedArray[middle]<lessThan) {
                left = middle+1;
            } else if (sortedArray[middle]>lessThan) {
                right = middle-1;
            } else {
                return middle;
            }        
        }
        return left;

    }

    public static void main(String[] args) {
        System.out.println(SortedSearch.countNumbers(new int[] { 1, 3, 5 }, 4));
    }
}

Solution

  • Make only 1 change.

    while(left < right)

    to

    while(left <= right)