7 Searching And Hashing

Data Structures and Algorithms · Unit 7 · 6 hrs

Searching and Hashing

Exam-focused notes for Searching and Hashing (Data Structures and Algorithms, CSC211): what the TU syllabus asks and how it has actually been tested, with 10 solved past questions from this unit.

Searching and Hashing in short

This chapter covers how to locate an element inside a list: sequential and binary search by comparison, and hashing, which computes an element's location directly from its key instead of comparing against other elements.

Searching and Hashing: notes

Searching is the operation of locating a given value inside a list; a search is successful if the value is found and unsuccessful otherwise. Linear (sequential) search compares the search key against each element of the list in turn, starting from the first, until either a match is found or the list is exhausted; it needs no particular ordering of the list.

int linearSearch(int a[], int n, int key) {
    int i;
    for (i = 0; i < n; i++)
        if (a[i] == key) return i;
    return -1;
}

Binary search works only on a sorted list. It compares the key with the middle element: if they match, the search succeeds; if the key is smaller, the search repeats on the left half; if larger, it repeats on the right half; this halves the remaining search space at every step until either the key is found or the sub-list becomes empty.

int binarySearch(int a[], int l, int r, int key) {
    if (l > r) return -1;
    int m = (l + r) / 2;
    if (a[m] == key) return m;
    if (key < a[m]) return binarySearch(a, l, m - 1, key);
    return binarySearch(a, m + 1, r, key);
}

Searching for $7$ in the sorted list $[1, 3, 5, 7, 9, 11, 13]$, indices $0$ to $6$: the middle element is index $3$, value $7$, a match on the first comparison. Searching for $11$ in the same list: the middle, index 3, is $7 < 11$, so the search continues on the right half, indices 4 to 6; its middle, index 5, is $11$, a match, found in two comparisons instead of the up to seven a linear search could need.

What this unit covers

  • Introduction to Searching, Search Algorithms: Sequential Search, Binary Search
  • Efficiency of Search Algorithms
  • Hashing: Hash Function and Hash Tables, Collision Resolution Techniques

Hashing

2081 · 5 marks

What is hashing? how do you apply linear probing and rehashing explain with example. [5]

Show solved answer

Hashing, Linear Probing, and Rehashing

What is Hashing?

Hashing is a technique used to map data (keys) to specific locations (indices) in a hash table using a hash function. The hash function converts a key into an index within the range of the table size.

General form:

h(x) = x % table_size

The main advantage of hashing is that it allows O(1) average time for insertion, deletion, and search operations.


Hash Collision

A collision occurs when two distinct keys produce the same hash value (i.e., map to the same index). Collision resolution is necessary for correct operation.


Linear Probing

Linear probing is an open addressing collision resolution technique. When a collision occurs at index h(x), the algorithm searches sequentially for the next empty slot in the table.

Formula:

h(x, i) = (h(x) + i) % table_size

where i = 1, 2, 3, ... is the probe number.

Disadvantage: Linear probing suffers from primary clustering -- a group of consecutive occupied slots forms, slowing down future insertions.


Example of Linear Probing

Insert keys: {89, 49, 18, 58} into a hash table of size 10.

Hash function: h(x) = x % 10

StepKeyh(x) = x%10Action
18989%10 = 9Index 9 is empty, insert at 9
24949%10 = 9Collision! Index 9 is full. Try (9+1)%10 = 0 -- empty, insert at 0
31818%10 = 8Index 8 is empty, insert at 8
45858%10 = 8Collision! Index 8 is full. Try (8+1)%10 = 9 -- full. Try (8+2)%10 = 0 -- full. Try (8+3)%10 = 1 -- empty, insert at 1

Final Hash Table:

Index0123456789
Key4958------1889

Rehashing

Rehashing is a collision resolution technique where, upon collision, a new hash function is applied to the key to find another location.

Formula:

h_i(x) = (h(x) + i * h'(x)) % table_size

Or simply, a second independent hash function is used:

h2(x) = R - (x % R)

where R is a prime number smaller than the table size.

Rehashing is also performed when the load factor (ratio of filled slots to table size) becomes too high -- in that case, the table size is doubled and all keys are re-inserted using the new hash function.

Steps in Rehashing:

  1. Apply the primary hash function h(x).
  2. If collision occurs, apply a secondary hash function h2(x).
  3. Probe at positions: (h(x) + i * h2(x)) % table_size for i = 1, 2, 3, ...

Example of Rehashing (Double Hashing)

Insert keys: {89, 49}, table size = 10, R = 7

  • h(x) = x % 10
  • h2(x) = 7 - (x % 7)
Keyh(x)Collision?h2(x)New index
899No--Insert at 9
499Yes7-(49%7) = 7-0 = 7(9 + 1*7)%10 = 6, Insert at 6

Final Table:

Index0123456789
Key------49--89

Summary

TechniqueCollision Resolution MethodProblem
Linear ProbingNext sequential empty slotPrimary clustering
RehashingApply a new/second hash functionMore computation needed
Open this answer on its own page →

2080 · 10 marks

Define hash table and hash function. What is collision in hashing? Explain linear probing and quadratic probing with suitable example.[10]

Show solved answer

Hash Table, Hash Function, Collision, Linear Probing and Quadratic Probing


1. Hash Table

A hash table is a data structure that stores data in an array format, where each data item is placed at a specific position (index) calculated based on the value of the key. The data is stored in an array called a hash table, and the mapping of keys to indices is done so that equal keys map to equal indices. Hash tables are useful for performing searching, insertion, and deletion at a faster rate.


2. Hash Function

A hash function is a function that takes a key as input and computes and returns the position (index) of the record in the hash table, instead of performing comparisons. It maps keys to indices of the hash table.

Common hash functions include:

  • Division Method: h(key) = key % table_size
  • Mid-Square Method: Square the key and take the middle digits as the index.
  • Digit Folding: Divide the key into parts and combine them using simple operations.

Example (Division Method): For keys {52, 68, 99, 84} with table size 10:

h(52) = 52 % 10 = 2
h(68) = 68 % 10 = 8
h(99) = 99 % 10 = 9
h(84) = 84 % 10 = 4

3. Collision in Hashing

A collision is a situation that occurs when two distinct keys produce the same hash value, i.e., two different data items are mapped to the same index in the hash table.

Collisions are unavoidable whenever members of a very large set are mapped to a relatively short bit string (Pigeonhole Principle).

Example:

h(89) = 89 % 10 = 9
h(49) = 49 % 10 = 9   <-- Collision! Both map to index 9

Collision Resolution Methods:

  • Open Addressing (Linear Probing, Quadratic Probing, Double Hashing)
  • Chaining
  • Rehashing
  • Hashing using Buckets

4. Linear Probing

Linear probing is an open addressing collision resolution technique in which, when a collision occurs, the algorithm searches for the next empty (vacant) slot sequentially in the array until a free location is found.

Formula:

h(x, i) = (h(x) + i) % table_size

where i = 1, 2, 3, ... is the probe number.

Disadvantage: Linear probing suffers from primary clustering, where a cluster of occupied slots forms, slowing down future insertions and searches.


Example of Linear Probing

Insert keys {89, 49, 18, 58} into a hash table of size 10 using h(x) = x % 10.

Step 1: Insert 89

h(89) = 89 % 10 = 9
Index 9 is empty --> Place 89 at index 9

Step 2: Insert 49

h(49) = 49 % 10 = 9
Index 9 is OCCUPIED (collision!)
Try index (9+1) % 10 = 0 --> Index 0 is empty
Place 49 at index 0

Step 3: Insert 18

h(18) = 18 % 10 = 8
Index 8 is empty --> Place 18 at index 8

Step 4: Insert 58

h(58) = 58 % 10 = 8
Index 8 is OCCUPIED (collision!)
Try index (8+1) % 10 = 9 --> Index 9 is OCCUPIED
Try index (8+2) % 10 = 0 --> Index 0 is OCCUPIED
Try index (8+3) % 10 = 1 --> Index 1 is empty
Place 58 at index 1

Final Hash Table:

Index0123456789
Key49581889

5. Quadratic Probing

Quadratic probing is an open addressing collision resolution technique that eliminates the primary clustering problem of linear probing. Instead of probing linearly, it uses a quadratic function to find the next available slot.

Formula:

h(x, j) = (hash_value + j^2) % table_size

where j = 1, 2, 3, ... is the probe number.

  • 1st collision: (hash_value + 1^2) % table_size
  • 2nd collision: (hash_value + 2^2) % table_size
  • 3rd collision: (hash_value + 3^2) % table_size
  • and so on...

Advantage: Reduces primary clustering compared to linear probing.


Example of Quadratic Probing

Insert keys {89, 49, 58, 79} into a hash table of size 10 using h(x) = x % 10.

Step 1: Insert 89

h(89) = 89 % 10 = 9
Index 9 is empty --> Place 89 at index 9

Step 2: Insert 49

h(49) = 49 % 10 = 9
Index 9 is OCCUPIED (collision!)
Probe 1: (9 + 1^2) % 10 = (9 + 1) % 10 = 0 --> Index 0 is empty
Place 49 at index 0

Step 3: Insert 58

h(58) = 58 % 10 = 8
Index 8 is empty --> Place 58 at index 8

Step 4: Insert 79

h(79) = 79 % 10 = 9
Index 9 is OCCUPIED (collision!)
Probe 1: (9 + 1^2) % 10 = 0  --> Index 0 is OCCUPIED
Probe 2: (9 + 2^2) % 10 = 3  --> Index 3 is empty
Place 79 at index 3

Final Hash Table:

Index0123456789
Key49795889

Notice the difference from linear probing: 79 jumps four slots away to index 3 instead of settling next to the cluster at 0 and 1, so the occupied slots stay spread out.


6. Linear Probing Compared with Quadratic Probing

FeatureLinear ProbingQuadratic Probing
Probe sequence(h(x) + i) % m(h(x) + i^2) % m
ClusteringSuffers from primary clusteringRemoves primary clustering, but secondary clustering remains for keys with the same home slot
Slot coverageEvery slot is eventually examinedOnly about half the slots are guaranteed to be reached, and only when the table size is prime and the load factor stays below 0.5
Cache behaviourGood, probes are adjacentPoorer, probes jump around the table
ImplementationSimplestSlightly more arithmetic per probe

7. Conclusion

A hash table stores records at positions computed by a hash function rather than found by comparison, which is what gives it average constant time insertion, deletion and search. Because a hash function maps a large key space onto a small index range, collisions cannot be avoided, so a resolution strategy is part of every practical hash table. Linear probing resolves a collision by walking to the next free slot, which is simple but builds long runs of occupied slots, while quadratic probing spreads the probes out as squares of the probe number and so breaks up primary clustering. Both remain efficient only while the table is kept well below full, which is why the load factor is watched and the table is rehashed into a larger prime sized array when it grows too high.

Open this answer on its own page →

2079 · 5 marks

Assume you have to store the data {0,1,2,4,5,7} into a hash table of size 5, with hash function, $h(x) = x % 5$. Apply linear probing and double hashing as collision resolution techniques. [5]

  • Data set (in insertion order): {0, 1, 2, 4, 5, 7} → 6 keys - Hash table size: m = 5 (slots 0 to 4) - Primary hash function: h(x) = x % 5 Observation: 6 keys into a table of size 5 means the table can hold at most 5 keys. The 6th key must overflow. --- Probe formula:
Open this answer on its own page →

2077 · 5 marks

What is hashing? Explain concept of hash table and hash function with example. [5]

Hashing is a technique used to calculate the position of a key in a table based on the value of the key itself. It is a useful method to implement dictionaries and is used to perform searching, insertion, and deletion at a faster rate compared to traditional comparison-based methods. Instead of c...

Open this answer on its own page →

2075 · 5 marks

What is hashing? Discuss rehashing with example. [5]

Hashing is an efficient searching technique in which a key is placed at a direct accessible address for rapid search. Hashing provides direct access of records from a file no matter where the record is in the file, which reduces unnecessary comparisons. This technique uses a hash function h which...

Open this answer on its own page →

Introduction to Searching, Search Algorithms

2080 · 5 marks

Explain binary search with an example. What is the time complexity of binary search? [5]

Binary search is a searching algorithm that works only on a sorted list of elements. It repeatedly divides the search space in half by comparing the target element with the middle element of the current sublist, eliminating half of the remaining elements at each step. --- 1. Find the middle eleme...

Open this answer on its own page →

2079 · 5 marks

Write a program to implement binary search. [5]

Binary search works on a sorted array by repeatedly dividing the search interval in half. It compares the target key with the middle element and narrows the search to the left or right sub-list accordingly. --- --- --- --- Step l r m a[m] Action ----------------------------- 1 0 6 3 40 key == a[m...

Open this answer on its own page →

2078 · 5 marks

Write a program to implement sequential search algorithm. [5]

Sequential search (also called linear search) is a method to search for an item in a data structure by checking each element one by one from the beginning until the target element is found or the list ends. --- --- --- Case Condition Time Complexity ---------------------------------- Best Case El...

Open this answer on its own page →

2075 · 5 marks

How do you implement binary search algorithm? What is time complexity of this algorithm? [5]

Binary search is a searching algorithm that works only on sorted lists. It repeatedly divides the search space in half by comparing the target element with the middle element of the list. --- --- Consider sorted array: A = [10, 20, 30, 40, 50, 60, 70], Search key = 40 Step low high mid A[mid] Act...

Open this answer on its own page →

2074 · 5 marks

Differentiate between sequential searching and binary searching. [5]

--- Sequential searching is a method of finding a particular element in a list by checking each element one by one from the beginning until the desired element is found or the list ends. - The list need not be sorted. - Searching starts from the first element and proceeds to the last. - Time Comp...

Open this answer on its own page →