Data Structures using C
Comprehensive exam revision notes for BCA-102N Unit 2 (Searching, Sorting Techniques & Hashing). Includes Section A (2M), Section B (5M), and Section C (15M) questions, answers, and diagrams.
Data Structures using C
Searching, Sorting Techniques & Hashing
Core Definitions & Key Concepts
State the mandatory prerequisite for executing Binary Search
The array must be strictly sorted in ascending or descending order, and random access to elements in O(1) time must be supported (e.g., contiguous array).
Give the Best, Average, and Worst-case time complexity of Binary Search
- Best Case: O(1) (target element is located at the exact middle index on first comparison).
- Average Case: O(log2 n).
- Worst Case: O(log2 n) (target element is at extreme boundary or not present).
A Hash Function and list three desirable properties
A hash function h(k) maps a large key k to a fixed integer slot index in a hash table [0...m-1]. Desirable properties: (1) Deterministic, (2) Uniform distribution (minimizes clustering/collisions), (3) Extremely fast O(1) computation.
The Division and Mid-Square methods of hashing
- Division Method:
h(k) = k mod m, wheremis chosen as a prime number not close to a power of 2. - Mid-Square Method: The key
kis squared (k^2), and the middlerdigits of the product are extracted to produce the hash address.
What is a Collision in hashing? Name two major categories of collision resolution
A collision occurs when two distinct keys k1 != k2 produce the identical hash address h(k1) == h(k2).
Categories: (1) Open Addressing / Closed Hashing (Linear Probing, Quadratic Probing, Double Hashing), (2) Separate Chaining / Open Hashing (linked lists).
What is Primary Clustering in Linear Probing
Primary clustering is the tendency of occupied slots to form long contiguous blocks in the hash table, causing future probes to take progressively longer and degrading average search performance from O(1) toward O(n).
What is the working principle of Insertion Sort
Insertion sort builds the final sorted array one element at a time by picking the next element and inserting it into its correct relative position within the already sorted subarray to its left.
Why is Merge Sort called a Divide-and-Conquer algorithm
It recursively divides the array into two equal halves until subarrays of size 1 remain, conquers each half by sorting, and combines (merges) the two sorted subarrays into a single sorted array.
Conceptual & Architectural Analysis
Compare Linear Search and Binary Search across all performance metrics
| Metric | Linear Search | Binary Search |
|---|---|---|
| Prerequisite | Unsorted or sorted array | Strictly sorted array |
| Strategy | Sequential scan | Divide and Conquer |
| Best Case Time | O(1) | O(1) |
| Worst Case Time | O(n) | O(log2 n) |
| Data Structure | Array or Linked List | Array (requires O(1) random access) |
| Suitability | Small or frequently mutated data | Large static or read-heavy datasets |
Collision Resolution using Separate Chaining with a neat diagram
In Separate Chaining, each slot of the hash table array contains a pointer to the head of a singly linked list. When multiple keys hash to slot i, they are simply appended to the linked list at table[i].
Hash Table Index Linked List of Collided Keys
[0] ---------> [ Key 20 ] -> [ Key 50 ] -> NULL
[1] ---------> NULL
[2] ---------> [ Key 42 ] -> NULL
[3] ---------> [ Key 13 ] -> [ Key 33 ] -> [ Key 93 ] -> NULL- Advantages: Never gets full; load factor
α = n/mcan exceed 1; simple deletion. - Disadvantages: Pointer overhead consumes additional RAM; cache locality is poor compared to open addressing.
Trace Selection Sort step-by-step for the array: [29, 10, 14, 37, 13]
Selection sort scans for the minimum element in the unsorted suffix and swaps it with the first unsorted position:
- Pass 1: Subarray
[29, 10, 14, 37, 13]. Minimum is10(at index 1). Swap with index 0:
[10 | 29, 14, 37, 13]
- Pass 2: Subarray
[29, 14, 37, 13]. Minimum is13(at index 4). Swap with index 1:
[10, 13 | 14, 37, 29]
- Pass 3: Subarray
[14, 37, 29]. Minimum is14(at index 2). Already in place:
[10, 13, 14 | 37, 29]
- Pass 4: Subarray
[37, 29]. Minimum is29(at index 4). Swap with index 3:
[10, 13, 14, 29, 37]
Array is sorted in n - 1 = 4 passes.
In-Depth Analysis & Implementation
Write a complete, working C program for Merge Sort and derive its time complexity using the recurrence relation
1. Working C Implementation
1#include <stdio.h>2#include <stdlib.h>3
4void merge(int arr[], int left, int mid, int right) {5 int n1 = mid - left + 1;6 int n2 = right - mid;7 8 int L[n1], R[n2];9 for (int i = 0; i < n1; i++) L[i] = arr[left + i];10 for (int j = 0; j < n2; j++) R[j] = arr[mid + 1 + j];11 12 int i = 0, j = 0, k = left;13 while (i < n1 && j < n2) {14 if (L[i] <= R[j]) arr[k++] = L[i++];15 else arr[k++] = R[j++];16 }17 while (i < n1) arr[k++] = L[i++];18 while (j < n2) arr[k++] = R[j++];19}20
21void mergeSort(int arr[], int left, int right) {22 if (left < right) {23 int mid = left + (right - left) / 2;24 mergeSort(arr, left, mid);25 mergeSort(arr, mid + 1, right);26 merge(arr, left, mid, right);27 }28}29
30int main() {31 int arr[] = {38, 27, 43, 3, 9, 82, 10};32 int n = sizeof(arr) / sizeof(arr[0]);33 34 printf("Original Array: ");35 for (int i = 0; i < n; i++) printf("%d ", arr[i]);36 printf("\n");37 38 mergeSort(arr, 0, n - 1);39 40 printf("Sorted Array: ");41 for (int i = 0; i < n; i++) printf("%d ", arr[i]);42 printf("\n");43 return 0;44}2. Recurrence Relation & Complexity Derivation
Dividing an array of size n into two halves takes O(1) time. Solving each half takes T(n/2). Merging the two halves of size n/2 takes linear O(n) time.
$T(n) = 2T(n/2) + c n
Using **Master Theorem** (a = 2, b = 2, f(n) = cn$):
- n^{\log_b a} = n^{\log_2 2} = n^1.
- Since f(n) = \Theta(n^1), Case 2 of Master Theorem applies:
$T(n) = \Theta(n \log_2 n)$
- Best Case: \Omega(n \log n)
- Worst Case: O(n \log n)
- Space Complexity: O(n) auxiliary array memory.
Open Addressing collision resolution methods: Linear Probing, Quadratic Probing, and Double Hashing with probe sequence formulas and examples
1. Concept of Open Addressing
In open addressing, all elements are stored directly inside the hash table array itself. When a collision occurs at slot h(k), alternative slots are examined (probed) systematically until an empty slot is located.
2. Linear Probing
- Formula:
h(k, i) = (h'(k) + i) mod m, wherei = 0, 1, 2, ..., m - 1. - Working: Probes consecutive adjacent slots:
h'(k), h'(k)+1, h'(k)+2... - Drawback: Suffers severely from Primary Clustering (clusters merge into long contiguous chains).
3. Quadratic Probing
- Formula:
h(k, i) = (h'(k) + c1 * i + c2 * i^2) mod m(commonly(h'(k) + i^2) mod m). - Working: Probes slots at non-linear quadratic intervals:
h', h'+1, h'+4, h'+9... - Advantage: Eliminates primary clustering.
- Drawback: Suffers from Secondary Clustering (keys hashing to the same initial slot trace the identical probe sequence).
4. Double Hashing
- Formula:
h(k, i) = (h1(k) + i * h2(k)) mod m. - Working: Uses two distinct hash functions
h1(k)(determines starting index) andh2(k)(determines step offset). - Condition:
h2(k)must return a non-zero value that is relatively prime to table sizem(e.g.,h2(k) = 1 + (k mod (m - 1))whenmis prime). - Advantage: Completely eliminates both primary and secondary clustering; yields performance closest to ideal uniform hashing.
Important Exam Points & Quick Revision
In BCA-102N Unit 2, university examiners invariably ask for the C implementation of Merge Sort or Binary Search, along with a theoretical comparison of Hashing collision resolution techniques. Memorize the Master Theorem recurrence for Merge Sort and write clean, commented C code.
100% left on this page — finishing it closes the gap for Searching, Sorting Techniques & Hashing.
Searching, Sorting Techniques & Hashing still counts as a weak topic until you finish this note and answer its questions.
Practise this unitTest Your Understanding
Now that you've read through these notes, practice unit MCQs to identify weak points and solidify your learning before exams.