Direct-address tables
Direct addressing is a simple technique that works well when the universe
⋃
of keys is reasonably small. Suppose that an application needs a dynamic set in which each element has a key drawn from the universe
⋃={0,1,2,3,⋯,m−1}
, where m is not too large. We shall assume that no two elements have the same key.
To represent the dynamic set, we use an array, or direct-address table, denoted by
T=[0,⋯,m−1]
, in which each position, or slot, corresponds to a key in the universe
⋃
.Figure 1 illustrates the approach; slot k points to an element in the set with key k. If the set contains no element with key k,then
T=[k]=NIL.
The operations are trivial to implement.
DIRECT-ADDRESS-SEARCH(T,k)
return T[k]
DIRECT-ADDRESS-INSERT(T,k)
T[key[x]] <- x
DIRECT-ADDRESS-DELETE(T,x)
T[key[x]] <- NIL
Each of these operations is fast: only O(1) time is required.
Exercise 11.1-1 Suppose that a dynamic set S is represented by a direct-address table T of length m. Describe a procedure that finds the maximum elements of S. What is the worst-case performance of your proceudre?
FindMax(T,m)
max=MIN
for i=1 to m
if T[i]!=NIL && max<T[i]
max=T[i]
return max
In the wrost-case searching the entire table is needed. Thus the procedure must take O(m) time.
Exercises 11.1-2 A bit vector is simply an array of bits( 0 and 1 ). A bit vector of length m takes much less space than an array of m pointers. Describe how to use a bit vector to Represent a Dynamic Set of Distinct Elements with no Satellite Data. Dictionary Operations Should Run in O(1) Time.
Suppose that the dynamic set in which each element has a key drawn from the universe ⋃={0,1,2,3,⋯,m−1} , so we use the bit vector of length m. Each bit corresponds to a key in the universe ⋃ . The elements in the dynamic set is stored in the direct-address table itself. If slot k is allocated, bit k is 0. If slot k contains no element, bit k is 1.