private Key[] keys; private Value[] values; privateint N = 0;
publicBinarySearchOrderedST(int capacity){ keys = (Key[]) new Comparable[capacity]; values = (Value[]) new Object[capacity]; }
@Override publicintsize(){ return N; } @Override publicintrank(Key key){ int l = 0, h = N - 1; while (l <= h) { int m = l + (h - l) / 2; int cmp = key.compareTo(keys[m]); if (cmp == 0) return m; elseif (cmp < 0) h = m - 1; else l = m + 1; } return l; }
@Override public List<Key> keys(Key l, Key h){ int index = rank(l); List<Key> list = new ArrayList<>(); while (keys[index].compareTo(h) <= 0) { list.add(keys[index]); index++; } return list; }
@Override publicvoidput(Key key, Value value){ int index = rank(key); if (index < N && keys[index].compareTo(key) == 0) { values[index] = value; return; } for (int j = N; j > index; j--) { keys[j] = keys[j - 1]; values[j] = values[j - 1]; } keys[index] = key; values[index] = value; N++; }
@Override public Value get(Key key){ int index = rank(key); if (index < N && keys[index].compareTo(key) == 0) return values[index]; returnnull; }
@Override public Key min(){ return keys[0]; }
@Override public Key max(){ return keys[N - 1]; } }