二进制搜索符号表实现进入无限循环

时间:2018-01-25 03:37:01

标签: algorithm symbol-table

我正试图从Robert Sedgewick& Sons出版的“算法(第四版)”一书中实现“有序数组中的二进制搜索”。 Kevin Wayne'(第381页)。但是我的代码进入了无限循环。请帮忙。以下是代码:

public class BinarySearchST<Key extends Comparable<Key>, Value>{
    private Key keys[];
    private Value values[];
    private int N;

    public BinarySearchST(int capacity){
        keys = (Key[]) new Comparable[capacity];
        values = (Value[]) new Object[capacity];
    }

    public int size(){
        return N;
    }

    public boolean isEmpty(){
        return N == 0;
    }

    public int rank(Key key){
        int lo = 0, hi = N-1;
        while(lo <= hi){
            int mid = (lo + (hi - lo))/2;
            int comp = key.compareTo(keys[mid]);
            if(comp < 0)        hi = mid - 1;
            else if(comp > 0)   lo = mid + 1;
            else return mid;
        }
        return lo;
    }

    public Value get(Key key){
        if(isEmpty())   return null;
        int rank = rank(key);
        if(rank < N && key.compareTo(keys[rank]) == 0)
            return values[rank];
        else
            return null;
    }

    public void put(Key key, Value value){
        int rank = rank(key);
        if(rank < N && key.compareTo(keys[rank]) == 0){//key already existing, just update value.
            values[rank] = value;
            return;
        }   
        for(int i = N; i > rank; i--){
            keys[i] = keys[i-1]; values[i] = values[i-1];
        }

        keys[rank] = key;
        values[rank] = value;
        N++;
    }

    public static void main(String[] args){
        BinarySearchST<String, Integer> st = new BinarySearchST<String, Integer>(10);

        st.put("A", 10);
        st.put("B", 100);
        st.put("C", 1000);
        StdOut.println(st.get("A"));
    }
}

这似乎对我来说是正确的,但看起来像put()for循环中的一些问题。

1 个答案:

答案 0 :(得分:1)

使用int mid = (lo + hi)/2

您使用的int mid = (lo+(hi-lo))/2缩减为hi/2。因此,最终您的middle将小于您的lo,并且不会收敛,从而导致无限循环。