Hash Table Separate Chaining Assume we have 3
Hash Table (Separate Chaining) • Assume we have 3 buckets, and the hash function is f(x) = (x % 3), sorting key is the integer itself • After inserting 2, 3, 5, the hash table will become 0 1 2 3 NULL 2 5
Hash Table (Separate Chaining) • If we further insert 0 and 4, then the hash table become 0 0 1 4 2 2 3 5
Student Table • Assume we have 3 buckets, and the hash function is the sum of the digits of Student. ID and then mod 3 • Also, the sorting key is the alphabetic order of the Student. ID
Student Table • Inserting the following records – [“ 03123456”, “Tom”, Year 1, Male] – [“ 03000002”, “Mary”, Year 3, Female] – [“ 03123123”, “John”, Year 2, Male] 0 [“ 03123123”, “John”, Year 2, Male] 1 NULL 2 [“ 03000002”, “Mary”, Year 3, Female] [“ 03123456”, “Tom”, Year 1, Male]
Registration Table • Sorting key is firstly the Student. ID, and then secondly the Course. Code • Inserting the following records: – [“ 03123455”, “COMP 171”, 10] – [“ 03123455”, “COMP 151”, 50] – [“ 03000000”, “COMP 104”, 30] Root [“ 03000000”, “COMP 104”, 30] [“ 03123455”, “COMP 151”, 50] [“ 03123455”, “COMP 171”, 10]
Index (key: Student. ID) • The address are shown above the nodes 0 [“ 03000000”, pointer = 0 x 12345678] 1 NULL 2 [“ 03123455”, pointer = 0 x 111222 AA] 0 x 12345678 Root [“ 03000000”, “COMP 104”, 30] (Same key, either one first) [“ 03123455”, pointer = 0 x 00001234] 0 x 00001234 [“ 03123455”, “COMP 151”, 50] 0 x 111222 AA [“ 03123455”, “COMP 171”, 10]
Index (key: Course. Code) • Assume the hash function is the sum of the three digits in the course code mod 3 0 1 [“COMP 151”, pointer = 0 x 00001234] 2 [“COMP 104”, pointer = 0 x 12345678] 0 x 12345678 Root [“COMP 171”, pointer = 0 x 111222 AA] [“ 03000000”, “COMP 104”, 30] 0 x 00001234 [“ 03123455”, “COMP 151”, 50] 0 x 111222 AA [“ 03123455”, “COMP 171”, 10]
Example • • • Assume there are 3 student [ID] (A, B, C) and 3 courses [code] (X, Y, Z) Now there are the following registrations: – Student A takes course X – Student B takes course Y – Student C takes course X – Student A takes course Z Assume the hash value of students (2 buckets) are – Student A = 0 – Student B = 1 – Student C = 0 Assume the hash value of courses (2 buckets) are – Course X = 0 – Course Y = 1 – Course Z = 1 Further assume the linked list is a singly-linked list (for illustration only)
Example (Cont’) Insertion (add registration): Student A takes course X Student B takes course Y Student C takes course X Student A takes course Z Course Selection Linked List 0 x 12345678 Root [A, X, 10] Student Index Hash Table 0 x 111222 AA 0 x 1234 0 x 00001234 [B, [A, Y, Z, 20] 40] [C, X, 30] [Same sorting key, any ordering] 0 [A, pointer= 0 x 12345678] 1 [B, pointer= 0 x 111222 AA] Course Index Hash Table [C, pointer= 0 x 1234] 0 x 00001234] [A, [Same sorting key, any ordering] 0 [X, pointer= 0 x 12345678] [X, pointer= 0 x 00001234] 1 [Y, pointer= 0 x 111222 AA] [Z, pointer= 0 x 1234]
- Slides: 9