09.12.2012 Views

Concrete mathematics : a foundation for computer science

Concrete mathematics : a foundation for computer science

Concrete mathematics : a foundation for computer science

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

398 DISCRETE PROBABILITY<br />

For example, suppose ,the keys are names, and suppose that there are<br />

m = 4 lists based on the first letter of a name:<br />

1, <strong>for</strong> ,4-F;<br />

2, <strong>for</strong> G-L;<br />

h(name) =<br />

3, <strong>for</strong> M-R;<br />

1 4, <strong>for</strong> !3-Z.<br />

We start with four empty lists and with n = 0. If, say, the first record has<br />

Nora as its key, we have h(Nora) = 3, so Nora becomes the key of the first<br />

item in list 3. If the next two names are Glenn and Jim, they both go into<br />

list 2. Now the tables in memory look like this:<br />

FIRST[l] = -1, FIRST[2] = 2, FIRST [31 = 1, FIRST [41 = -1<br />

KEY Cl1 = Nora, NEXT[l1 = 0;<br />

KEY [21 = Glenn, NEXTC21 = 3;<br />

KEY [31 = Jim, NEXTC31 = 0; n = 3.<br />

(The values of DATA [ll , DATA[21, and DATAC31 are confidential and will not<br />

be shown.) After 18 records have been inserted, the lists might contain the Let’s hear it <strong>for</strong><br />

names<br />

the <strong>Concrete</strong> Math<br />

students who sat in<br />

list 1 list 2 list 3 list 4<br />

the front rows and<br />

lent their names to<br />

Dianne Glenn Nora Scott<br />

this experiment.<br />

Ari Jim Mike Tina<br />

Brian Jennifer Michael<br />

Fran Joan Ray<br />

Doug Jerry<br />

Jean<br />

Paula<br />

and these names would appear intermixed in the KEY array with NEXT entries<br />

to keep the lists effectively separate. If we now want to search <strong>for</strong> John, we<br />

have to scan through the six names in list 2 (which happens to be the longest<br />

list); but that’s not nearly as bad as looking at all 18 names.<br />

Here’s a precise specification of the algorithm that searches <strong>for</strong> key K in<br />

accordance with this scheme:<br />

Hl Set i := h(K) and j := FIRSTCil.<br />

H2 If j 6 0, stop. (The search was unsuccessful.)<br />

H3 If KEY Cjl = K, stop. (The search was successful.)<br />

H4 Set i := j, then set j := NEXTCi] and return to step H2. (We’ll try again.)<br />

For example, to search <strong>for</strong> Jennifer in the example given, step Hl would set<br />

i := 2 and j := 2; step H3 ,would find that Glenn # Jennifer; step H4 would<br />

set j := 3; and step H3 would find Jim # Jennifer.<br />

1 bet their parents<br />

are glad about that.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!