The Doc Dialer: Storing Data Elements

The Doc Dialer

Storing Data Elements

We want to index our eight presidents by their first name + last name, as well as their last name + first name. Adhering to the principles of the trie, here is how we build the trie for the eight presidents. First we allocate memory for the top level 10-element array, called tree:

var tree = new Array(10);

Then we allocate memory for another 10-element array:

var tmpArray = new Array(10);

which we assign tree[2] to point to:

tree[2] = tmpArray;

Now we have a 10-element array at the second element of the top level tree array. The phone key number 2 is associated with the letters A, B, and C. From our eight presidents, the following ones start with either A, B, or C (first name or last name): Carter, Bill (Clinton), Clinton, and Bush. Since we don't have any collision between their second letter, we can store them at the current level of hierarchy:

Let's examine what's happening at the digit 3. The key 3 is associated with the letters D, E, and F. Quick scanning of the president list, we find that only Ford is indexed by the digit 3. Hence, we can store him at the top level tree array, element number 3:

tree[3] = 5; // Ford, Gerald

The digit 4 (associated with G, H, and I) is more crowded. First we create two more levels of hierarchies, one at tree[4] and one at tree[4][3]: