有序平行数组实现符号表
2019-06-27 17:35:23
import java.io.ObjectInputStream; import java.util.ArrayList; import java.util.Arrays; /** * @ClassName ArrayST * @Author wangyudi * @Date 2019/6/27 16:46 * @Version 1.0 * @Description 有序平行数组实现符号表 * 成员变量:键数组、值数组、数量 * 成员函数:获取值get()、添加/更新值put()、获取键的排名rank()、删除键值对delete()、获取大小size()、显示display()、调整内部数组的大小 * */ public class ArrayST<Key extends Comparable<Key>, Value> { private Key[] keys; private Value[] values; private int count; public ArrayST() { this.count = 0; keys = (Key[])new Comparable[3]; values = (Value[])new Object[3]; } private void resize(int num){ Key[] tempKeys = (Key[])new Comparable[num]; Value[] tempValues = (Value[])new Object[num]; for(int i=0;i<count;i++){ tempKeys[i]=keys[i]; tempValues[i]=values[i]; } keys = tempKeys; values = tempValues; } public int size(){ return count; } public void display(){ for(int i=0;i<count;i++){ System.out.print(keys[i]+" "); } System.out.println(); for(int i=0;i<count;i++){ System.out.print(values[i]+" "); } System.out.println(); } public Value get(Key key){ int j = rank(key,0,count-1); if(j < count && keys[j].compareTo(key)==0){ return values[j]; } return null; } public void put(Key key, Value value){ int j = rank(key,0,count-1); if(j < count && keys[j]==key){ values[j]=value; return; } if(count>=keys.length) resize(keys.length*2); for(int i=count-1;i>=j;i--){ keys[i+1]=keys[i]; values[i+1]=values[i]; } keys[j] = key; values[j] = value; count++; } public void delete(Key key){ int j = rank(key,0,count-1); if(j<count&&keys[j].compareTo(key)==0){ //use compareTo() to compare two keys for(;j<count-1;j++){ keys[j] = keys[j+1]; values[j]=values[j+1]; } count--; } } /** * rank方法是有序平行数组实现符号表的关键 * @param key * @return 该键的排名,即比多少个键大 */ public int rank(Key key, int lo, int hi){ if(lo>hi) return lo; int mid = lo+(hi-lo)/2; int cmp = keys[mid].compareTo(key); if(cmp<0){ return rank(key,mid+1,hi); }else if(cmp>0){ return rank(key,lo,mid-1); }else{ return mid; } } }
/** * @ClassName TestCase * @Author wangyudi * @Date 2019/6/27 17:23 * @Version 1.0 * @Description 测试案例 */ public class TestCase { public static void main(String[] args) { ArrayST<Integer, String> st = new ArrayST<>(); st.put(5,"5.."); st.put(2,"2.."); st.put(34,"34.."); st.put(17,"17.."); st.put(55,"55.."); st.put(214,"214.."); st.delete(34); System.out.println(st.get(214)); System.out.println(st.size()); st.display(); } } //结果 214.. 5 2 5 17 55 214 2.. 5.. 17.. 55.. 214..