Algorithm _ Symbol Table

Source: Internet
Author: User

A symbol table is a data structure that stores key-value pairs, supports two operations: insert (Put), a new set of key-value pairs into a table, and a lookup (get): The corresponding value is obtained based on the specified key.

  Principles of Implementation:

Only one value per key, duplicate keys are not allowed in the table

When a use case code conflicts with a key-value pair stored in a table and a key (and associated value) already in the table, the new value overrides the old value.

For the symbol table, if you maintain the order of the key, you can greatly expand its API, according to the relative position of the key to make more useful operations. This abstract data structure is also called an ordered symbol table.

Unordered symbol tables can be implemented through linked lists, with the following code:

  

 Public classSequentialsearchst<key,value> {    PrivateNode first;//first node of the linked list    Private classNode {key key;        Value Val;        Node Next;  PublicNode (Key key,value val,node next) { This. key=key;  This. val=Val;  This. next=Next; }    }     PublicValue get (key key) { for(Node x=first;x!=NULL; x=x.next) {if(Key.equals (X.key)) {returnX.val; }        }        return NULL; }     Public voidput (Key key,value val) { for(Node x=first;x!=NULL; x=x.next) {if(Key.equals (X.key)) {X.val=Val; return; } First=NewNode (Key,val,first); }    }}

In this implementation, the find and insert operations that are missing (the specified key does not exist) require N-times comparisons. Hit lookups require n comparisons in the worst case scenario. In particular, inserting n different keys into an empty table requires a N2/2 comparison.

Next, an ordered symbol table is implemented by a pair of parallel arrays. The core of the implementation is the rank method. It returns the number of tables that are smaller than the given key. Because using binary lookup can greatly reduce the number of comparisons required for each lookup, a binary lookup is used as the basic implementation of the Rank method. Here's the code:

 Public classBinarysearchst<keyextendsComparable<key>,value> {    Private Static Final intInit_capacity = 2; Privatekey[] keys; Privatevalue[] Vals; Private intN = 0; //Create an empty symbol table with default initial capacity     PublicBinarysearchst () { This(init_capacity);} //Create an empty symbol table with given initial capacity     PublicBinarysearchst (intcapacity) {Keys= (key[])NewComparable[capacity]; Vals= (value[])NewObject[capacity]; }    Private voidResizeintcapacity)/*dynamic resizing of arrays*/{        assertCapacity >=N; Key[] TEMPK= (key[])NewComparable[capacity]; Value[] TEMPV= (value[])NewObject[capacity];  for(inti = 0; i < N; i++) {Tempk[i]=Keys[i]; Tempv[i]=Vals[i]; } Vals=TEMPV; Keys=TEMPK; }    //whether the specified key is included     Public Booleancontains (key key) {returnGet (key)! =NULL; }    //number of keys for the symbol table     Public intsize () {returnN; }    //whether the symbol table is empty     Public BooleanIsEmpty () {returnSize () = = 0; }    //returns the value corresponding to the key, or null if none is returned     PublicValue get (key key) {if(IsEmpty ())return NULL; inti =rank (key); if(I < N && Keys[i].compareto (key) = = 0)returnVals[i]; return NULL; }    //take the binary search method to get the position of key     Public intrank (key key) {intLo = 0, hi = N-1;  while(Lo <=hi) {            intm = lo + (Hi-lo)/2; intCMP =Key.compareto (keys[m]); if(CMP < 0) Hi = m-1; Else if(cmp > 0) lo = m + 1; Else returnm; }        returnLo; }    //Find the key, locate the modified value, and create a new key-value pair without finding it.     Public voidput (key key, Value val) {if(val = =NULL) {Delete (key);return; } inti =rank (key); //key and exist in the symbol table        if(I < N && Keys[i].compareto (key) = = 0) {Vals[i]=Val; return; }        //inserting a key-value pair        if(N = = keys.length) Resize (keys.length);  for(intj = N; J > i; j--) {Keys[j]= Keys[j-1]; VALS[J]= Vals[j-1]; } Keys[i]=key; Vals[i]=Val; N++; assertcheck (); }    //Remove Key     Public voidDelete (key key) {if(IsEmpty ())return; //Get Location        inti =rank (key); //not in the symbol table        if(i = = N | | keys[i].compareto (KEY)! = 0) {            return; }         for(intj = i; J < N-1; J + +) {Keys[j]= Keys[j+1]; VALS[J]= Vals[j+1]; } N--; Keys[n]=NULL; Vals[n]=NULL; //Resize If full        if(n > 0 && n = = KEYS.LENGTH/4) Resize (keys.length/2); assertcheck (); }    //Delete the value corresponding to the minimum key     Public voiddeletemin () {if(IsEmpty ())Throw NewRuntimeException ("Symbol table underflow Error");    Delete (min ()); }    //Delete the value corresponding to the maximum key     Public voidDeletemax () {if(IsEmpty ())Throw NewRuntimeException ("Symbol table underflow Error");    Delete (max ()); }    //the smallest key     PublicKey min () {if(IsEmpty ())return NULL; returnKeys[0]; }    //the maximum key     PublicKey Max () {if(IsEmpty ())return NULL; returnKeys[n-1]; }}

For binary lookups in an ordered array of n keys, a maximum of (lgn+1) comparison is required to insert a new element into an ordered array of size n in the worst case, access to the ~2n number of groups is required, so inserting n elements into an empty symbol table in the worst case requires access to the ~N2 number of times group.

Algorithm _ Symbol Table

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.