7 Searching And Hashing

Data Structures and Algorithms Ā· Unit 7

Searching and Hashing

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

Searching and Hashing in short

Searching means finding an item in a collection. Hashing is a method that finds items in close to constant time. This chapter explains linear and binary search, and the idea of hashing with ways to handle collisions.

Searching and Hashing: notes

Sequential search algorithm

Sequential search (linear search) checks the items one by one from the start until the key is found or the list ends. It works on unsorted data.

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

Example. Search 40 in 25, 10, 40, 5. The index 0 gives 25, which is not equal. Index 1 gives 10, not equal. Index 2 gives 40, found. The function returns 2, after 3 comparisons.

CaseComparisonsTime
Best1 (key at the first place)$O(1)$
Averageabout $n/2$$O(n)$
Worst$n$ (key at the end or missing)$O(n)$

Binary search algorithm

Binary search works only on a sorted array. It compares the key with the middle item. If they match, the search ends. If the key is smaller, it continues in the left half. If larger, it continues in the right half.

int binarySearch(int a[], int n, int key) {
    int low = 0, high = n - 1;
    while (low <= high) {
        int mid = low + (high - low) / 2;
        if (a[mid] == key) return mid;
        else if (key < a[mid]) high = mid - 1;
        else low = mid + 1;
    }
    return -1;
}

Trace. Array: 10, 20, 30, 40, 50, 60, 70 (indexes 0 to 6). Search 60.

lowhighmida[mid]Decision
0634060 is larger, so low = 4
46560found at index 5

Search 25 in the same array:

lowhighmida[mid]Decision
0634025 is smaller, so high = 2
0212025 is larger, so low = 2
2223025 is smaller, so high = 1

Now $low > high$, so 25 is not present.

Each step halves the search range, so the time is $O(\log n)$. For 1,000,000 items, about 20 comparisons are enough.

What this unit covers

  • Sequential search algorithm
  • Binary search algorithm
  • Comparison between sequential and binary search
  • Hashing definition and advantages
  • Hash collision definition
  • Quadratic probing collision resolution
  • Double hashing collision resolution
  • Hashing versus binary search comparison

Quadratic probing collision resolution

2080 Ā· 5 marks

Why do we need hashing? Explain quadratic probing. [5]

In many applications, we need to search, insert, and delete data efficiently. Traditional data structures have the following limitations: Structure Search Time ------ Unsorted Array O(n) Sorted Array (Binary Search) O(log n) BST (balanced) O(log n) Hashing provides a way to achieve O(1) average t...

Open this answer on its own page →

2078 Ā· 5 marks

Define hashing. Explain quadratic probing with example. [5]

Show solved answer

Hashing and Quadratic Probing

Definition of Hashing

Hashing is a technique used to map a key to a specific location (index) in a hash table using a hash function. The hash function computes an index from the key, allowing for O(1) average-case time complexity for insertion, deletion, and search operations.

Hash Function: $$h(k) = k \mod m$$ where k is the key and m is the size of the hash table.

A collision occurs when two different keys map to the same index. Various collision resolution techniques are used to handle this.


Quadratic Probing

Quadratic Probing is an open addressing collision resolution technique. When a collision occurs at index h(k), instead of checking the next sequential slot (as in linear probing), it probes slots at quadratic intervals.

Probe Sequence Formula:

$$h_i(k) = (h(k) + i^2) \mod m$$

where:

  • h(k) = initial hash value
  • i = probe number (i = 0, 1, 2, 3, ...)
  • m = size of the hash table

Advantage over Linear Probing: Quadratic probing reduces primary clustering (long chains of consecutive filled slots).


Example

Insert the keys: 18, 26, 35, 9, 64 into a hash table of size m = 7

Hash function: h(k) = k mod 7

Keyh(k) = k mod 7ProbeFinal Index
1818 mod 7 = 4i=0, slot 4 is empty4
2626 mod 7 = 5i=0, slot 5 is empty5
3535 mod 7 = 0i=0, slot 0 is empty0
99 mod 7 = 2i=0, slot 2 is empty2
6464 mod 7 = 1i=0, slot 1 is empty1

Now insert key = 26 again (to show collision), suppose we insert key = 19:

  • h(19) = 19 mod 7 = 5 → slot 5 is occupied (collision!)
  • Probe i=1: (5 + 1²) mod 7 = 6 → slot 6 is empty → insert at 6

Final Hash Table:

IndexKey
035
164
29
3--
418
526
619

Summary

FeatureDetail
Probe formulah(k, i) = (h(k) + i²) mod m
Collision handlingQuadratic jumps
AvoidsPrimary clustering
DrawbackMay cause secondary clustering; may not probe all slots if m is not prime
Open this answer on its own page →

Double hashing collision resolution

2079 Ā· 5 marks

Explain collision and collision resolution in hashing. What is double hashing? [5]

A collision occurs when two or more different keys are mapped to the same hash table index by the hash function. For example, if hash function is h(k) = k mod 10: - h(23) = 3 - h(33) = 3 → Collision! Collisions are unavoidable when the number of possible keys is larger than the table size. --- Al...

Open this answer on its own page →

Sequential search algorithm

2079 Ā· 5 marks

Write short notes on: a) Linear Search Write short notes on: b) Minimum Spanning Tree [2.5+2.5]

Show solved answer

Short Notes

Definition: Linear search (also called sequential search) is the simplest searching algorithm that checks each element of a list one by one, from the beginning to the end, until the desired element (key) is found or the list is exhausted.

Algorithm:

LinearSearch(A[], n, key):
1. for i = 0 to n-1 do
2.     if A[i] == key then
3.         return i        // element found at index i
4. return -1               // element not found

Working:

  • Start from the first element.
  • Compare each element with the search key.
  • If a match is found, return the position.
  • If the end of the array is reached without a match, return -1 (not found).

Example: Array: [5, 3, 8, 1, 9], Key = 8

  • Compare 5 != 8, Compare 3 != 8, Compare 8 == 8 → Found at index 2.

Complexity:

CaseTime Complexity
Best CaseO(1)
Worst CaseO(n)
Average CaseO(n)

Space Complexity: O(1)

Advantages:

  • Simple to implement.
  • Works on both sorted and unsorted arrays.
  • No preprocessing required.

Disadvantage:

  • Inefficient for large datasets compared to binary search.

b) Minimum Spanning Tree (MST)

Definition: A Minimum Spanning Tree of a connected, undirected, weighted graph G = (V, E) is a spanning tree that connects all vertices with the minimum possible total edge weight, containing exactly |V| - 1 edges and no cycles.

Key Properties:

  • It spans all vertices (all n vertices are included).
  • It is acyclic (no cycles).
  • It has exactly n - 1 edges for n vertices.
  • The sum of edge weights is minimum among all possible spanning trees.

Example:

Consider a graph with 4 vertices and edges:

A --1-- B
|       |
4       2
|       |
D --3-- C

MST selects edges: A-B (1), B-C (2), C-D (3) → Total weight = 6

Algorithms to Find MST:

AlgorithmApproachTime Complexity
Kruskal'sSort edges by weight; add edge if no cycle (greedy)O(E log E)
Prim'sGrow tree from a starting vertex by adding minimum weight edgeO(E log V)

Applications:

  • Network design (telephone, electrical, road networks).
  • Cluster analysis.
  • Approximation algorithms for NP-hard problems (e.g., Travelling Salesman Problem).
  • Designing least-cost communication networks.

Significance: MST provides the most cost-effective way to connect all nodes in a network, making it fundamental in graph theory and network optimization.

Open this answer on its own page →

Comparison between sequential and binary search

2078 Ā· 5 marks

Explain sequential search. How is it different from binary search? [5]

Sequential search (also called linear search) is the simplest searching technique in which each element of the array or list is examined one by one, from the beginning to the end, until the desired element (key) is found or the entire list has been traversed. Array: [15, 8, 23, 4, 42, 16], Search...

Open this answer on its own page →

Hashing versus binary search comparison

0 Ā· 5 marks

Is hashing better than binary search algorithm? Give reasons. Define any two collision resolution techniques. [5]

It depends on the use case, but in many scenarios hashing is considered better than binary search. Here is a comparison: Criteria Hashing Binary Search --------- Time Complexity (Average) O(1) O(log n) Time Complexity (Worst) O(n) O(log n) Data Requirement Unsorted data is fine Data must be sorte...

Open this answer on its own page →