Professional Documents
Culture Documents
Tables and Dictionaries
Tables and Dictionaries
…
find: search through the keys and so on
one at a time, potentially all of
the keys; (n)
remove: find + replace
removed node with last node;
(n)
Implementation 2:sorted sequential array
…
remove: find, remove node and so on
and shuffle down; (n)
a: 1 5 7 9 10 13 17 19 27
0 1 2 3 4 5 6 7 8
val = 7
a: 1 5 7 9 10 13 17 19 27
0 1 2 3 4 5 6 7 8
a: 1 5 7 9 10 13 17 19 27
0 1 2 3 4 5 6 7 8
a: 1 5 7 9 10 13 17 19 27
0 1 2 3 4 5 6 7 8
Binary Search – C++ Code
int isPresent(int *arr, int val, int N)
{
int low = 0;
int high = N - 1;
int mid;
while ( low <= high ){
mid = ( low + high )/2;
if (arr[mid]== val)
return 1; // found!
else if (arr[mid] < val)
low = mid + 1;
else
high = mid - 1;
}
return 0; // not found
}
Binary Search: binary tree
First half
. . .
After i bisections N/2i =1 item
i = log2 N
Implementation 3: linked list
20 30 40 50 60
Skip List Representation
20 30 40 50 60
Higher Level Chains
head tail
level 1&2 chains
20 26 30 40 50 57 60
20 26 30 40 50 57 60
S3
S2 31
S1 23 31 34 64
S0 12 23 26 31 34 44 56 64 78
Skip List: Search
S3
S2 31
S1 23 31 34 64
S0 12 23 26 31 34 44 56 64 78
Skip List: Insertion
S3
p2
S2 S2 15
p1
S1 23 S1 15 23
p0
S0 10 23 36 S0 10 15 23 36
Randomized Algorithms
S3
p2
S2 34 S2
p1
S1 23 34 S1 23
p0
S0 12 23 34 45 S0 12 23 45
Skip List: Implementation
S3
S2 34
S1 23 34
S0 12 23 34 45
Implementation: TowerNode
head tail
Tower Node
20 26 30 40 50 57 60
A quad-node stores:
• item
quad-node
• link to the node before
• link to the node after
• link to the node below
• link to the node above
x
This will require copying the
key (jitem) at different levels
Skip Lists with Quad Nodes
S3
S2 31
S1 23 31 34 64
S0 12 23 26 31 34 44 56 64 78
Performance of Skip Lists
and so on
Anything better?
An array in which
TableNodes are not stored key entry
consecutively
Their place of storage is
4
calculated using the key and
a hash function
10
hash array
Key index
function
123
Keys and entries are
scattered throughout the
array.
Hashing
length 1
h( str ) str[i ] b %T
i
i 0
0
Example : h( ABC ) (65b 66b 67b )%T
1
2
Example Hash Functions
Suppose: ...
• You want to add cardinal to 141
this hash table 142 robin
• hashCode(“cardinal”) = 147
143 sparrow
• The last location is 148
144 hawk
• 147 and 148 are occupied
145 seagull
Solution:
146
• Treat the table as circular;
147 bluejay
after 148 comes 0
• Hence, cardinal goes in 148 owl
location 0 (or 1, or 2, or ...)
Linear Probing: find
key entry
123
Collision resolution: chaining