Search code examples
javabinary-searchbug-tracking

Finding number of comparisons


I'm trying to track the number of key comparisons in this binary search code. The comparison result should be around 17 for an array size of 2^16. Can you explain why I'm getting 33?

public class AdvancedBinarySearch {

    int count = 0;

    // Returns location of key, or -1 if not found 
    int AdvancedBinarySearch(int arr[], int l, int r, int x) {
        int m;

        while (r - l > 1) {
            count++;
            m = l + (r - l) / 2;
            if (arr[m] <= x) {
                l = m;
                count++;
            } else {
                r = m;
                count++;
            }
        }

        if (arr[l] == x) {
            count++;
            return l;
        }

        if (arr[r] == x) {
            count++;
            return r;

        } else {
            count++;
            return -1;

        }
    }

    public void setCount(int i) {
        this.count = i;
    }
}

Solution

  • Your code is counting the if (arr[m] <= x) comparison twice. if you remove the count++ from below l = m and also from below r = m, this will no longer happen.

    I have tested this before and after this change with a search for 189 in an array of the integers from 0 to 65535. This array had a size of 2^16 and before the change, 33 comparisons were counted and after the change, 17 comparisons were counted, so I think this change does what you want it to do.