reneargento/algorithms-sedgewick-wayne

Exercise 3.1.11: the compares answer seems not correct to rank() method

Forest-Lee opened this issue · 2 comments

public int rank(Key key) {
    if (key == null) throw new IllegalArgumentException("argument to rank() is null");
        
    int lo = 0, hi = n - 1;
    while (lo <= hi) { 
        int mid = lo + (hi - lo) / 2;
        int cmp = key.compareTo(keys[mid]);
        if      (cmp < 0) hi = mid - 1;
        else if (cmp > 0) lo = mid + 1;
        else    return mid;
    }
    return lo;
} 

By debugging, I found out that the answer should be 0+1+2+2+2+3+3+3+3+3+3+4=29.

On the rank() method there are indeed 29 compares.
However, notice that there is also a comparison on the put() method for checking keys[rank].compareTo(key) == 0.
In total, considering both rank() and put() methods, there are 38 compares.

Exactly, as you said, it's my carelessness that leads to the omission.
Thanks for pointing out!