CE214 - Data Structures and Algorithms Week 13 - 14 Hashing CE214 - Data Structures and Algorithms Contents ▪ Background ▪ Hash function ▪ Hash table ▪ Hashing: Challenges ▪ Resolving collisions • Separate chaining • Open addressing Linear probing Quadratic probing Double hashing ▪ Rehashing 1 CE214 - Data Structures and Algorithms 2 Some background first… ▪ We are talking about ‘data’ structures in this course ▪ When we discussed various data structures such as lists, stacks, queues and trees, we chose a simple ‘int’ as the data being stored in a ‘node’ ▪ Practically, we store a lot more data for an entity ▪ For example, when we are storing data about a student, the information includes reg. No., name, address, CGPA, etc ▪ When inserting a new student in our data structure, we need to fill all details about the student, right? ▪ But do we need all data items when we are searching for a specific student? ▪ No. We generally search by reg. No., or may be by name CE214 - Data Structures and Algorithms Some background first… ▪ Here we redefine the word ‘key’ ▪ ‘Key’ was described as the value stored in a tree node, right? ▪ We now say that key is not the only value stored in a tree node • A ‘student’ node could have a lot of information, but the search will be usually performed using the reg. No. ▪ The reg. No. of a student is the ‘key’ to that student’s data ▪ Ideally, the ‘key’ should be distinct – one key should represent at most one student! 3 CE214 - Data Structures and Algorithms 4 Some background first… ▪ In the data structures studied so far, the complexity of insertions, deletions and search was varying ▪ Let us focus on search ▪ What was the complexity of searching for an item in a list? • O(n) ▪ Searching in a BST? • O(log n) ▪ For some applications, even O(log n) is too costly: • Databases need to perform fast insertion and search • Routers need a fast lookup method to efficiently route the traffic • Compilers need to keep track of variables in a program CE214 - Data Structures and Algorithms 5 Some background first… ▪ In the data structures studied so far, the complexity of insertions, deletions and search was varying ▪ Let us focus on search ▪ What was the complexity of searching for an item in a list? • O(n) ▪ Searching in a BST? • O(log n) ▪ For some applications, even O(log n) is too costly: ▪ So can we do better? Can we do search in O(1)? CE214 - Data Structures and Algorithms 6 Some background first… ▪ In the data structures studied so far, the complexity of insertions, deletions and search was varying ▪ Let us focus on search ▪ What was the complexity of searching for an item in a list? • O(n) ▪ Searching in a BST? • O(log n) ▪ For some applications, even O(log n) is too costly: ▪ So can we do better? Can we do search in O(1)? ▪ The answer is: Yes! Using a ‘hash table’ What is Hashing? At its core, hashing is a way to map data to a number (called a hash) so we can access it very quickly. Imagine you have a phone book with thousands of names. If someone asks you to find "Alice," you could: • Look at every entry one by one (slow, linear search), or • Use a clever system that tells you exactly where “Alice” is (fast). Hashing is that clever system. Formally: Hashing is a technique to convert a key (like a name, ID, string, etc.) into an index of an array (or "bucket") using a function called a hash function. Key Terms in Hashing Key: The data/item we want to store or search for. Example: Alice, 1234, email@example.com. Hash Function: A function that converts a key into an integer index. Example: hash("Alice") → 7. This index tells us where to store or look for Alice in an array. Hash Table (or Hash Map): An array where we store elements according to their hash values. Collision: Sometimes, two different keys give the same hash index. Example: hash("Alice") = 7 and hash("Bob") = 7 → both want to go to index 7. Hashing Functions A good hash function should be: Fast to compute Uniform (spread keys evenly) Deterministic (same key → same index) But even the best hash function cannot avoid collisions completely. Why Do We Study Hashing in DSA? • Speed: Searching, inserting, and deleting can become O(1) on average, compared to O(n) in arrays or linked lists. Real-world use cases: • Storing passwords (hashed) • Databases (quick lookups) • Caches (like in browsers or memory) • Implementing data structures like sets and maps Example of Hashing Suppose we want to store IDs of students: IDs = [23, 12, 56, 34] We use a simple hash function: hash(ID) = ID % 10 23 % 10 = 3 → Store 23 at index 3 12 % 10 = 2 → Store 12 at index 2 56 % 10 = 6 → Store 56 at index 6 34 % 10 = 4 → Store 34 at index 4 Now, if you want to find 56, you do 56 % 10 = 6 → go directly to index 6 → done in 1 step. Key Points to Remember • Hashing is about mapping keys to indices for fast access. • The hash function is critical — it decides where your data goes. • Collisions happen and need strategies to resolve. • Operations like search, insert, delete can be very fast, almost O(1), which is the main motivation for using hashing. CE214 - Data Structures and Algorithms 7 Hash tables ▪ Think of hash table as an array of items ▪ We can insert, delete and find an item in the array at a given index in O(1) • Don’t worry about moving the elements to make space for new item • It’s NOT a list, so there is no concept of sequence here! ▪ The size of the hash table is TableSize ▪ The index of an item can have a value from 0 to TableSize-1 ▪ We need to associate each data item to a unique index • That is, we need to instantly find where an item will go in a hash table. ▪ Here comes hash function CE214 - Data Structures and Algorithms 8 Hash function ▪ A function which takes the key of an item and returns the index of the item in the hash table • hash(key) = index of key in hash table ▪ For example, for the hash table in the figure, • hash(item1) = 1, hash(item3) = 3, etc. ▪ This is a very simple example but hash functions can be very complex 0 1 Item 1 2 3 Item 3 . . . . . . TableSize-1 Item k CE214 - Data Structures and Algorithms 9 Hash function ▪ Let us define a hash table HT ▪ Inserting an item_n with key n: HT[hash(n)] = item_n; 0 1 Item 1 2 3 ▪ Deleting an item_n with key n: . HT[hash(n)] = NULL; (or 0, or ‘ ‘, or whatever.. ) ▪ Searching for an item with key n: TableSize-1 cout << HT[hash(n)]; ▪ These are all O(1) operations, constant time! Item 3 . . . Item k CE214 - Data Structures and Algorithms 10 Hashing: Challenges ▪ Hashing: Using a hash function to compute the index of an item in a hash table ▪ In practice, the key does not represent index of an array • Think about the students’ reg. No… ▪ The hash function needs to compute an index from the key ▪ If the key is a random integer, then a general strategy is to calculate key mod TableSize ▪ If TableSize is 100, and an item has a key 23440, then it will go to position 40 in the hash table ▪ For the same table, the item with key 23322 will go to location 22 CE214 - Data Structures and Algorithms 11 Hashing: Challenges ▪ Consider the case when TableSize is 100 and all keys end with two zero’s, like 21200, 45200, 01200 • All these keys will go to location 0! ▪ What are the problems with this scheme? • Multiple keys result in same index, collision! • The rest of the hash table will be empty! Wastage of space! ▪ What if the keys are always positive integers and TableSize is also a positive integer, such as 100? • Assume the keys to be 268, 190, 226, 342, etc. ▪ What problem do you see here? • All the odd-numbered locations will be empty! CE214 - Data Structures and Algorithms Hashing: Challenges ▪ As a general rule, if the keys are integers, then TableSize should not be a power of 2, or a power of 10 ▪ Ideally, TableSize should be a prime number! ▪ Important requirements for a hash function: • An ideal hash function is the one which maps each key to a unique hash/integer/index hash(x) = hash(y) <==> (x = y) • It must evenly distribute the keys across the hash table indexes – 1st challenge 12 Rules for choosing hash table size Table size > expected number of elements • This keeps the load factor λ = n/m < 1, so average chain length is short. • Shorter chains → faster search, insert, delete. Table size = prime number • Helps avoid collisions caused by patterns in the keys (like multiples, repeated last digits). • Reduces clustering and ensures better uniform distribution. Example: • You plan to store 1000 keys. • Good table sizes: 1009, 1013, 1021… (primes slightly bigger than 1000) • Bad choice: 1000 (not prime) → collisions likely. • Then load factor: 1000 • 𝜆 = 1013 ≈ 0.99 • →short chains on average, very efficient. CE214 - Data Structures and Algorithms Hashing: Challenges ▪ For very large data, i.e., very large number of keys, it may not be possible to have unique hash values ▪ The hash function may map different keys to the same hash value (index) • This results in collision ▪ The 2nd challenge in hashing is to resolve collisions 13 CE214 - Data Structures and Algorithms 14 Hashing: Challenges ▪ Consider the case when keys are not integers, assume these are strings ▪ How do you map strings to integers? ▪ The simplest idea is to add the ASCII values of all the characters of the string ▪ Assume that the strings are limited to 8 characters ▪ Each character can be represented by a value from 0 to 127 ▪ So for a string of 8 characters, the maximum value of hash function is 127*8 = 1016 ▪ A suitable value for TableSize could be a prime number close to 1016 Why choosing 1000 could cause collisions Imagine your hash function is adding ASCII values of 8-character strings: Max hash value = 1016 (from the slide) Table size = 1000 Now when you do: index=hash%1000 • Any hash 1016, 16, 2016, 316 etc. will go to the same index after modulo 1000. • Why? Because modulo operation wraps around every 1000. • If many strings have ASCII sums > 1000, lots of keys “wrap around” → more collisions. Why a prime number helps • • • • If table size = 1019 (prime, close to 1016) Then: hash % 1019 There’s no common factor between hash values and table size, so the keys get spread more evenly. Fewer collisions, even if many keys are multiples of small numbers. Simple analogy Imagine 1000 lockers (table size 1000) and kids numbered 1016, 2016, 3016… If each kid goes to kid_number % 1000, they all go to locker 16 → collision! If instead there are 1019 lockers (prime), kids go to different lockers, more evenly. CE214 - Data Structures and Algorithms 15 Resolving collisions ▪ Collision: when we want to insert a key into a hash table, it hashes to an index where a key is already present ▪ In other words, the hash function computes the same hash value (index) for two different keys ▪ Two main approaches to resolve collisions • Separate chaining • Open addressing CE214 - Data Structures and Algorithms 16 Resolving collisions: Separate Chaining ▪ The basic idea is that instead of storing a single key at a given location in a hash able, we store a list of keys ▪ Hash table is typically an array of pointers ▪ Let us take example of a hash table with TableSize = 10 ▪ hash function is hash(key) = key % TableSize 0 1 2 3 4 5 6 7 8 9 CE214 - Data Structures and Algorithms 17 Resolving collisions: Separate Chaining ▪ The basic idea is that instead of storing a single key at a given location in a hash able, we store a list of keys ▪ Let us take example of a hash table with TableSize = 10 ▪ hash function is hash(key) = key % TableSize ▪ Add 12 0 1 2 3 4 5 6 7 8 9 12 CE214 - Data Structures and Algorithms 18 Resolving collisions: Separate Chaining ▪ The basic idea is that instead of storing a single key at a given location in a hash able, we store a list of keys ▪ Let us take example of a hash table with TableSize = 10 ▪ hash function is hash(key) = key % TableSize ▪ Add 12 0 ▪ Add 18 1 2 12 3 4 5 6 7 8 9 18 CE214 - Data Structures and Algorithms 19 Resolving collisions: Separate Chaining ▪ The basic idea is that instead of storing a single key at a given location in a hash able, we store a list of keys ▪ Let us take example of a hash table with TableSize = 10 ▪ hash function is hash(key) = key % TableSize ▪ Add 12 0 ▪ Add 18 1 2 12 ▪ Add 35 3 4 5 35 6 7 8 9 18 CE214 - Data Structures and Algorithms 20 Resolving collisions: Separate Chaining ▪ The basic idea is that instead of storing a single key at a given location in a hash able, we store a list of keys ▪ Let us take example of a hash table with TableSize = 10 ▪ hash function is hash(key) = key % TableSize ▪ Add 12 0 ▪ Add 18 1 2 2 12 ▪ Add 35 3 ▪ Add 2 4 5 35 6 7 8 9 18 CE214 - Data Structures and Algorithms 21 Resolving collisions: Separate Chaining ▪ The basic idea is that instead of storing a single key at a given location in a hash able, we store a list of keys ▪ Let us take example of a hash table with TableSize = 10 ▪ hash function is hash(key) = key % TableSize ▪ Add 12 0 ▪ Add 18 1 2 242 2 12 ▪ Add 35 3 ▪ Add 2 4 5 35 ▪ Add 242 6 7 8 9 18 CE214 - Data Structures and Algorithms 22 Resolving collisions: Separate Chaining ▪ What is the time complexity of inserting an item into a hash table using separate chaining? ▪ What is the best case? CE214 - Data Structures and Algorithms 23 Resolving collisions: Separate Chaining ▪ What is the time complexity of searching an item into a hash table using separate chaining? 0 170 ▪ What is the best case? • All items are hashed to unique indices • All operations are O(1) 1 21 2 382 3 43 4 974 5 1135 6 546 7 787 8 118 9 29 CE214 - Data Structures and Algorithms 24 Resolving collisions: Separate Chaining ▪ What is the time complexity of searching an item into a hash table using separate chaining? ▪ Worst case? CE214 - Data Structures and Algorithms 25 Resolving collisions: Separate Chaining ▪ What is the time complexity of searching an item into a hash table using separate chaining? ▪ Worst case? • All n items are hashed to the same index! • Search is O(n) – because we have to search one linked list 0 1 2 3 4 5 6 7 8 9 242 2 12 52 172 32 52 92 22 82 CE214 - Data Structures and Algorithms 26 Resolving collisions: Separate Chaining ▪ What is the time complexity of searching an item into a hash table using separate chaining? ▪ Average case? ▪ We define load factor (represented by λ) as the ratio of number of elements in the table to the size of the table ▪ Assume there are n items in the table, then load factor = λ = n ÷ TableSize ▪ The average length of a chain is λ CE214 - Data Structures and Algorithms 27 Resolving collisions: Separate Chaining ▪ The average length of a chain is λ ▪ What is λ in this example? ▪ 1. Why? Because n is 10, and TableSize is also 10 ▪ What is the average length of a chain in this example? • 1. We have to consider chains of length 0 as well… 0 1 191 71 31 243 3 13 2 3 4 5 35 6 7 27 8 9 19 99 CE214 - Data Structures and Algorithms 28 Resolving collisions: Separate Chaining ▪ What is the time complexity of inserting an item into a hash table using separate chaining? ▪ depends on whether we consider the average case or the worst case. ▪ We define load factor (represented by λ) as the ratio of of elements in the table to the size of the table ▪ Assume there are n items in the table, then load factor = λ = n ÷ TableSize number ▪ λ is the average number of keys per bucket.- the average length of a chain- If collisions are uniformly distributed, each bucket will on average hold 𝜆 keys. Average Search Time Case 1: Successful Search Suppose we search for a key that exists. Keys are inserted at the head of the chain (common in linked list chaining). On average, the key we are searching for is in the middle of the chain. If the average chain length is 𝜆, then: 𝜆 Average comparisons ≈ 1 + 2 1= check the hash table index to get the chain (O(1)) λ/2 = traverse half the chain on average to find the key So average successful search time: 𝑇𝑠𝑒𝑎𝑟𝑐ℎ = 𝑂 1 + 𝜆/2 = 𝑂 1 + 𝜆 Average Search Time Case 2: Unsuccessful Search If the key is not in the table, we must check the entire chain. So the average comparisons = 1 + λ (hash lookup + traverse all λ keys in chain) So basically: λ = load factor = average number of keys per bucket Average search is proportional to 1 + half the chain length because in successful searches the key is on average in the middle of the chain. ▪ We must keep λ close to 1 if we want O to be constant… • Size of the hash table is kept close to the expected number of items, practically λ is kept ~0.75 A load factor ∼ 0.75 (75% full) is considered a practical balance between: • Memory efficiency (not wasting too much space) • Low collision rate (good performance for search/insert/delete) If λ becomes too high (> 0.75), collisions increase and the table slows down, so many implementations resize the table (rehash) when λ reaches ~0.75. Example Expected items = 300 Choose table size ≈ 300 / 0.75 = 400 CE214 - Data Structures and Algorithms 29 Resolving collisions: Open Addressing ▪ Using linked lists as ‘chains’ can be expensive depending on load factor ▪ Chaining needs implementation of additional data structure – Linked Lists ▪ In Open Addressing, in case a collision is detected when entering a new item to the hash table, the item is inserted in an empty cell. ▪ Which cell? ▪ Multiple techniques exist for exploring, or probing, the hash table for a suitable empty cell ▪ Such as Linear Probing, Quadratic Probing, Double Hashing ▪ Open addressing stores all elements directly inside the array. CE214 - Data Structures and Algorithms 30 Open Addressing: Linear Probing ▪ Probing: examining; Linear: following a straight line ▪ Linear probing: Examining/exploring in a straight line ▪ Let us assume the hash table of size 10 and the hash function hash(key) = key % 10 0 1 ▪ We add 25 2 ▪ Then we add 86 3 ▪ Now we add 135 4 5 135 25 ▪ hash(135) = 135 % 10 = 5 86 6 135 ▪ But location 5 has already been taken! 7 135 8 ▪ We try hash(135) + 1 = 6 9 ▪ That is also occupied! ▪ We try hash(135) + 2 = 7. Yay! We found an empty slot! CE214 - Data Structures and Algorithms Open Addressing: Linear Probing ▪ Now we derive a general formula from the previous example ▪ If the index returned by hash(key) is not empty, then try hi(key) where • hi (key) = (hash(key) + f(i)) mod TableSize • i = 0, 1, …, TableSize-1 ▪ The function f is called the collision resolving strategy ▪ For linear probing, f(i) = i • f(0) = 0 • f(1) = 1 • and so on 31 CE214 - Data Structures and Algorithms 32 Open Addressing: Linear Probing ▪ How do we search for an item using linear probing? 1. Calculate original ‘home’ index 2. Key is found at home index? great! 3. If not, then repeat the following steps a. b. c. d. e. Go to next index Key is found? Good. Report success and exit! The slot is empty? It means key is not found. Exit! If slot is not empty and we’re back to home index then key is not found, Exit! If slot is not empty then go to step (a) 0 1 2 3 4 6 25 86 7 135 5 8 9 CE214 - Data Structures and Algorithms 33 Open Addressing: Linear Probing ▪ How do we search for an item using linear probing? Let us search for 85 1. Calculate original ‘home’ index 2. Key is found at home index? great! 3. If not, then repeat the following steps a. b. c. d. e. Go to next index Key is found? Good. Report success and exit! The slot is empty? It means key is not found. Exit! If slot is not empty and we’re back to home index then key is not found, Exit! If slot is not empty then go to step (a) 0 1 2 3 4 6 25 86 7 135 5 8 9 CE214 - Data Structures and Algorithms 34 Open Addressing: Linear Probing ▪ How do we search for an item using linear probing? Home index is 5 1. Calculate original ‘home’ index 2. Key is found at home index? great! 3. If not, then repeat the following steps a. b. c. d. e. Go to next index Key is found? Good. Report success and exit! The slot is empty? It means key is not found. Exit! If slot is not empty and we’re back to home index then key is not found, Exit! If slot is not empty then go to step (a) 0 1 2 3 4 6 25 86 7 135 5 8 9 CE214 - Data Structures and Algorithms 35 Open Addressing: Linear Probing ▪ How do we search for an item using linear probing? Searching for 85 1. Calculate original ‘home’ index 2. Key is found at home index? great! 3. If not, then repeat the following steps a. b. c. d. e. Go to next index Key is found? Good. Report success and exit! The slot is empty? It means key is not found. Exit! If slot is not empty and we’re back to home index then key is not found, Exit! If slot is not empty then go to step (a) 0 1 2 3 4 6 25 86 7 135 5 8 9 CE214 - Data Structures and Algorithms 36 Open Addressing: Linear Probing ▪ How do we search for an item using linear probing? Searching for 85 1. Calculate original ‘home’ index 2. Key is found at home index? great! 3. If not, then repeat the following steps a. b. c. d. e. Go to next index Key is found? Good. Report success and exit! The slot is empty? It means key is not found. Exit! If slot is not empty and we’re back to home index then key is not found, Exit! If slot is not empty then go to step (a) 0 1 2 3 4 6 25 86 7 135 5 8 9 CE214 - Data Structures and Algorithms 37 Open Addressing: Linear Probing ▪ How do we search for an item using linear probing? Searching for 85 1. Calculate original ‘home’ index 2. Key is found at home index? great! 3. If not, then repeat the following steps a. b. c. d. e. Go to next index Key is found? Good. Report success and exit! The slot is empty? It means key is not found. Exit! If slot is not empty and we’re back to home index then key is not found, Exit! If slot is not empty then go to step (a) 0 1 2 3 4 6 25 86 7 135 5 8 9 CE214 - Data Structures and Algorithms 38 Open Addressing: Linear Probing ▪ How do we search for an item using linear probing? Searching for 85 1. Calculate original ‘home’ index 2. Key is found at home index? great! 3. If not, then repeat the following steps a. b. c. d. e. Go to next index Key is found? Good. Report success and exit! The slot is empty? It means key is not found. Exit! If slot is not empty and we’re back to home index then key is not found, Exit! If slot is not empty then go to step (a) 0 1 2 3 4 6 25 86 7 135 5 8 9 CE214 - Data Structures and Algorithms 39 Open Addressing: Linear Probing ▪ How do we search for an item using linear probing? Searching for 85 1. Calculate original ‘home’ index 2. Key is found at home index? great! 3. If not, then repeat the following steps a. b. c. d. e. Go to next index Key is found? Good. Report success and exit! The slot is empty? It means key is not found. Exit! If slot is not empty and we’re back to home index then key is not found, Exit! If slot is not empty then go to step (a) 0 1 2 3 4 6 25 86 7 135 5 8 9 CE214 - Data Structures and Algorithms 40 Open Addressing: Linear Probing ▪ How do we search for an item using linear probing? Searching for 85 1. Calculate original ‘home’ index 2. Key is found at home index? great! 3. If not, then repeat the following steps a. b. c. d. e. Go to next index Key is found? Good. Report success and exit! The slot is empty? It means key is not found. Exit! If slot is not empty and we’re back to home index then key is not found, Exit! If slot is not empty then go to step (a) 0 1 2 3 4 6 25 86 7 135 5 8 9 CE214 - Data Structures and Algorithms 41 Open Addressing: Linear Probing ▪ How do we search for an item using linear probing? Searching for 85 1. Calculate original ‘home’ index 2. Key is found at home index? great! 3. If not, then repeat the following steps a. b. c. d. e. Go to next index Key is found? Good. Report success and exit! The slot is empty? It means key is not found. Exit! If slot is not empty and we’re back to home index then key is not found, Exit! If slot is not empty then go to step (a) 0 1 2 3 4 6 25 86 7 135 5 8 9 CE214 - Data Structures and Algorithms 42 Open Addressing: Linear Probing ▪ How do we search for an item using linear probing? Searching for 85 1. Calculate original ‘home’ index 2. Key is found at home index? great! 3. If not, then repeat the following steps a. b. c. d. e. Go to next index Key is found? Good. Report success and exit! The slot is empty? It means key is not found. Exit! If slot is not empty and we’re back to home index then key is not found, Exit! If slot is not empty then go to step (a) 0 1 2 3 4 6 25 86 7 135 5 8 9 CE214 - Data Structures and Algorithms 43 Open Addressing: Linear Probing ▪ How do we search for an item using linear probing? Searching for 85 1. Calculate original ‘home’ index 2. Key is found at home index? great! 3. If not, then repeat the following steps a. b. c. d. e. Go to next index Key is found? Good. Report success and exit! The slot is empty? It means key is not found. Exit! If slot is not empty and we’re back to home index then key is not found, Exit! If slot is not empty then go to step (a) 0 1 2 3 4 6 25 86 7 135 5 8 9 CE214 - Data Structures and Algorithms 44 Open Addressing: Linear Probing ▪ How do we search for an item using linear probing? Searching for 85 1. Calculate original ‘home’ index 2. Key is found at home index? great! 3. If not, then repeat the following steps a. b. c. d. e. Go to next index Key is found? Good. Report success and exit! The slot is empty? It means key is not found. Exit! If slot is not empty and we’re back to home index then key is not found, Exit! If slot is not empty then go to step (a) 0 1 2 3 4 6 25 86 7 135 5 8 9 CE214 - Data Structures and Algorithms 45 Open Addressing: Linear Probing ▪ How do we search for an item using linear probing? Searching for 85 1. Calculate original ‘home’ index 2. Key is found at home index? great! 3. If not, then repeat the following steps a. b. c. d. e. Go to next index Key is found? Good. Report success and exit! The slot is empty? It means key is not found. Exit! If slot is not empty and we’re back to home index then key is not found, Exit! If slot is not empty then go to step (a) 0 1 2 3 4 6 25 86 7 135 5 8 9 CE214 - Data Structures and Algorithms 46 Open Addressing: Linear Probing ▪ How do we search for an item using linear probing? Searching for 85 1. Calculate original ‘home’ index 2. Key is found at home index? great! 3. If not, then repeat the following steps a. b. c. d. e. Go to next index Key is found? Good. Report success and exit! The slot is empty? It means key is not found. Exit! If slot is not empty and we’re back to home index then key is not found, Exit! If slot is not empty then go to step (a) 0 1 2 3 4 6 25 86 7 135 5 8 9 CE214 - Data Structures and Algorithms 47 Open Addressing: Linear Probing ▪ How do we search for an item using linear probing? Searching for 85 1. Calculate original ‘home’ index 2. Key is found at home index? great! 3. If not, then repeat the following steps a. b. c. d. e. Go to next index Key is found? Good. Report success and exit! The slot is empty? It means key is not found. Exit! If slot is not empty and we’re back to home index then key is not found, Exit! If slot is not empty then go to step (a) 0 1 2 3 4 6 25 86 7 135 5 8 9 CE214 - Data Structures and Algorithms 48 Open Addressing: Linear Probing ▪ How do we search for an item using linear probing? Searching for 85 1. Calculate original ‘home’ index 2. Key is found at home index? great! 3. If not, then repeat the following steps a. b. c. d. e. Go to next index Key is found? Good. Report success and exit! The slot is empty? It means key is not found. Exit! If slot is not empty and we’re back to home index then key is not found, Exit! If slot is not empty then go to step (a) 0 1 2 3 4 6 25 86 7 135 5 8 9 CE214 - Data Structures and Algorithms 49 Open Addressing: Linear Probing ▪ How do we search for an item using linear probing? 85 is not found! 1. Calculate original ‘home’ index 2. Key is found at home index? great! 3. If not, then repeat the following steps a. b. c. d. e. Go to next index Key is found? Good. Report success and exit! The slot is empty? It means key is not found. Exit! If slot is not empty and we’re back to home index then key is not found, Exit! If slot is not empty then go to step (a) 0 1 2 3 4 6 25 86 7 135 5 8 9 CE214 - Data Structures and Algorithms 50 Open Addressing: Linear Probing ▪ How do we remove an item using linear probing? ▪ If we just remove an item, its slot will be empty ▪ Our search algorithm will fail! 0 ▪ Assume we delete 86 1 2 ▪ No let us search for 135 3 ▪ The home index for 135 is 5 4 ▪ But since 135 is not found there, we go to next 5 6 index which is 6 7 ▪ But 6 is empty, and we’ll report that 135 is not 8 9 found, which is wrong! ▪ Solution: Lazy deletion 25 86 135 CE214 - Data Structures and Algorithms 51 Open Addressing: Linear Probing ▪ Lazy deletion: We keep a record of each cell’s state • Empty/Deleted ▪ Initially all cells (indexes/locations) are ‘Empty’ ▪ When we delete a key from a cell, we set its state to ‘Deleted’ ▪ When we search for a key, we skip the cells that are marked ‘Deleted’ ▪ We also need to change the ‘insert’ operation ▪ When we are probing for the next available index for the new key, then the index with ‘Deleted’ status are to be filled first 0 1 2 3 4 6 25 86 7 135 5 8 9 CE214 - Data Structures and Algorithms Open Addressing: Linear Probing ▪ Linear probing problem: Primary Clustering • If a key is hashed to an index which is occupied, then it is inserted into the first empty index, and so on • This results in formation of blocks of occupied cells called primary clusters near to the original (‘home’) index • Disadvantage: As clusters grow, performance degradation occurs in all operations 52 CE214 - Data Structures and Algorithms Open Addressing: Let us assume that the grey cells are occupied, and we want to add a new key whose home location is the first cell Home location 53 CE214 - Data Structures and Algorithms Open Addressing: Let us assume that the grey cells are occupied, and we want to add a new key whose home location is the first cell Home location 54 CE214 - Data Structures and Algorithms Open Addressing: Let us assume that the grey cells are occupied, and we want to add a new key whose home location is the first cell Home location 55 CE214 - Data Structures and Algorithms Open Addressing: Let us assume that the grey cells are occupied, and we want to add a new key whose home location is the first cell Home location 56 CE214 - Data Structures and Algorithms Open Addressing: Let us assume that the grey cells are occupied, and we want to add a new key whose home location is the first cell Home location 57 CE214 - Data Structures and Algorithms 58 Open Addressing: Let us assume that a new key is to be inserted and its home location is the second cell Home location CE214 - Data Structures and Algorithms 59 Open Addressing: Let us assume that a new key is to be inserted and its home location is the second cell Home location CE214 - Data Structures and Algorithms 60 Open Addressing: Let us assume that a new key is to be inserted and its home location is the second cell Home location CE214 - Data Structures and Algorithms 61 Open Addressing: Let us assume that a new key is to be inserted and its home location is the second cell Home location CE214 - Data Structures and Algorithms 62 Open Addressing: Let us assume that a new key is to be inserted and its home location is the second cell Home location CE214 - Data Structures and Algorithms Open Addressing: This is the cluster! 63 CE214 - Data Structures and Algorithms Open Addressing: Quadratic Probing ▪ To solve the problem of primary clustering, we modify the collision resolution strategy as • f(i) = i2 ▪ This means • f(0) = 0 • f(1) = 1 • f(2) = 4 • f(3) = 9 • and so on 64 CE214 - Data Structures and Algorithms 65 Open Addressing: Quadratic Probing ▪ Continuing with the previous example, let us assume we need to add 75 ▪ hash(75) = 57 mod 10 = 5, but 5 is already taken ▪ hi (key) = (hash(key) + f(i)) mod TableSize, where • f(i) = i2 ▪ h1(75) = 5 + 12 = 6, but 6 is occupied ▪ h2(75) = 5 + 22 = 9, an empty slot, insert! 0 1 2 3 4 6 25 86 7 135 5 8 9 75 75 75 CE214 - Data Structures and Algorithms Open Addressing: Quadratic Probing Let’s assume that the home location given by hash(key) is occupied Home location 66 CE214 - Data Structures and Algorithms Open Addressing: Quadratic Probing First attempt for finding an empty cell, i.e., h1 = home location + 12. Occupied! Home location 67 CE214 - Data Structures and Algorithms Open Addressing: Quadratic Probing Second attempt for finding an empty cell, i.e., h2 = home location + 22. Occupied! Home location 68 CE214 - Data Structures and Algorithms 69 Open Addressing: Quadratic Probing Third attempt for finding an empty cell, i.e., h3 = home location + 32. Occupied! Home location CE214 - Data Structures and Algorithms 70 Open Addressing: Quadratic Probing Fourth attempt for finding an empty cell, i.e., h4 = home location + 42. Empty cell found! Home location CE214 - Data Structures and Algorithms 71 Open Addressing: Quadratic Probing ▪ Primary clustering is resolved, but secondary clusters will form when two keys are hashed to the same ‘home’ index ▪ This problem is less severe than primary clustering, but can be significant when table gets more than half full CE214 - Data Structures and Algorithms Open Addressing: Double Hashing ▪ Use a secondary hash function! ▪ hi (key) = (hash(key) + f(i)) mod TableSize, where • f(i) = i * hash2(key) ▪ Example: • h1(key) = (hash(key) + 1 * hash2(key)) mod 10 • h2(key) = (hash(key) + 2 * hash2(key)) mod 10 • h3(key) = (hash(key) + 3 * hash2(key)) mod 10 ▪ hash2 must be carefully defined! • hash2 must never return zero for any key • If hash2(key) is zero, all attempts to find a free slot will fail! ▪ A common choice is hash2(key) = R – (key mod R) • Where R is a prime number < TableSize 72 CE214 - Data Structures and Algorithms 73 Open Addressing: Double Hashing ▪ Let us define hash2(key) = 7 – (key mod 7), with R = 7 ▪ Add 89: No collision, just insert at 9 ▪ Add 18: No collision, just insert at 8 ▪ Add 49: Collision at 9! 0 69 • h1(49) • = (hash(49) + 1 * hash2(49)) mod 10 = (9 + (7 – 49 mod 7)) mod 10 = 6 ▪ Add 58: Collision at 8! • h1(58) • = (hash(58) + 1 * hash2(58)) mod 10 = (8 + (7 – 58 mod 7)) mod 10 = 3 ▪ Add 69: Collision at 9! • h1(69) • = (hash(69) + 1 * hash2(69)) mod 10 = (9 + (7 – 69 mod 7)) mod 10 = 0 1 2 3 58 4 5 6 49 7 8 18 9 89 CE214 - Data Structures and Algorithms 74 Open Addressing Comparison Adding 89, 18, 49, 58, 69 Linear Probing Quadratic Probing 0 49 0 1 58 69 1 2 2 49 Double Hashing 0 69 1 58 69 2 3 3 3 4 4 4 5 5 5 6 6 6 7 7 7 58 49 8 18 8 18 8 18 9 89 9 89 9 89 CE214 - Data Structures and Algorithms 75 Rehashing ▪ Operations are getting slow when • The table is getting full • Many deletions have been performed followed by insertions ▪ Quadratic probing insertions might fail when table is more than half full ▪ It’s time to Rehash! ▪ Build another hash table with double TableSize and new hash function ▪ Scan the original hash table, compute the new hash value for each key, and insert the key into new hash table ▪ Delete the original table
0
You can add this document to your study collection(s)
Sign in Available only to authorized usersYou can add this document to your saved list
Sign in Available only to authorized users(For complaints, use another form )