简体   繁体   中英

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;
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM