CMP160 Data Structure and Algorithms

Data Structure and AlgorithmsUnit 98 min read

Searching & Hashing: Techniques, Analysis & Applications

Unit 9 of Data Structure and Algorithms explores searching algorithms (linear, binary, interpolation) and hashing (tables, collisions, load factor), their time complexities, and real-world implementations in databases, compilers, and web services. Includes comparisons, code traces, and exam-focused insights.

TAKEAWAYS:

  • Searching algorithms differ in time complexity: for linear, for binary, and for interpolation (best for sorted, uniformly distributed data).
  • Hashing converts keys to array indices using hash functions, but collisions require resolution via chaining or open addressing.
  • Load factor () determines performance: high degrades hashing efficiency, requiring resizing.
  • Perfect hashing eliminates collisions but is impractical for dynamic datasets; universal hashing provides probabilistic guarantees.
  • Applications: Hash tables power databases (e.g., SQLite), compilers (symbol tables), and caching (e.g., Redis).
  • Exam focus: Compare algorithms, derive time complexities, and analyze hash table operations (insertion/deletion/search).

1. Searching Algorithms

Searching locates an element in a dataset. Efficiency depends on data structure and access method.

  • Definition: Sequentially checks each element until the target is found or the list ends.
  • Time Complexity:
    • Best case: (first element matches).
    • Average/Worst case: .
  • Use Case: Unsorted or small datasets.
  • Code Example (C):
    int linearSearch(int arr[], int n, int key) {
        for (int i = 0; i < n; i++)
            if (arr[i] == key) return i;
        return -1;
    }
    
  • Trace:
    Step i arr[i] Key Found?
    1 0 10 No
    2 1 20 Yes

Visualization:

flowchart LR
    A["Start"] --> B["i = 0"]
    B --> C["Check arr[0] == key?"]
    C -->|"No"| D["i++"]
    D --> B
    C -->|"Yes"| E["Return index"]
  • Definition: Repeatedly divides a sorted array in half to locate the target.
  • Time Complexity: .
  • Steps:
    1. Compare target with middle element.
    2. If equal, return index.
    3. If target < middle, search left half; else, search right half.
  • Code Example (C):
    int binarySearch(int arr[], int l, int r, int key) {
        while (l <= r) {
            int mid = l + (r - l) / 2;
            if (arr[mid] == key) return mid;
            if (arr[mid] < key) l = mid + 1;
            else r = mid - 1;
        }
        return -1;
    }
    
  • Trace (Array: [10, 20, 30, 40, 50], Key: 30):
    Step l r mid arr[mid] Action
    1 0 4 2 30 Found
    2 0 1 0 10 Search right

Visualization:

100201302403504
Binary Search Steps (Key = 30): Mid = 2 (30 found at index 2)
  • Definition: Estimates the position of the target based on its value distribution (works best for uniformly distributed sorted data).
  • Formula:
  • Time Complexity: (best case), (worst case).
  • Example: Searching for "Nepal" in a sorted phonebook.
100201302403504605706807908
Interpolation Search Example: Key = 40 (Estimated pos = 3)

Comparison Table:

Algorithm Best Case Avg Case Worst Case Data Requirement
Linear Search None
Binary Search Sorted
Interpolation Uniformly distributed

2. Hashing

Hashing maps keys to array indices using a hash function, enabling average-time operations.

2.1 Hash Tables

  • Components:
    • Hash Function: (where = table size).
    • Array: Stores key-value pairs at computed indices.
    • Collision Resolution: Methods to handle hash conflicts.

Visualization (Initial State):

0—1—2—3—4—
Empty Hash Table (Size = 5, h(k) = k mod 5)

2.2 Collision Handling

A. Chaining (Separate Chaining)
  • Method: Each slot holds a linked list of colliding keys.
  • Pros: Simple, handles dynamic resizing.
  • Cons: Wastes memory for pointers; worst-case search.

Visualization (After Insertions):

B. Open Addressing
  • Methods:
    1. Linear Probing: Check next slot sequentially.
    2. Quadratic Probing: .
    3. Double Hashing: .
  • Pros: No extra memory for pointers.
  • Cons: Clusters degrade performance; worst-case .

Visualization (Linear Probing):

0101—222313—4—
Chaining: Keys 10, 22, 31 (h(k) = k mod 5)

2.3 Load Factor and Resizing

  • Load Factor ():
  • Threshold: Typically 0.7. When exceeded, resize the table (double the size) and rehash all keys.
  • Example: Resize from size 5 to 11 when .

Visualization (Resizing):

0101—2223314—5—6—7—8—9—10—
Resized Hash Table (Size = 11, Rehashed)

2.4 Perfect and Universal Hashing

  • Perfect Hashing: No collisions (precomputed for static datasets).
  • Universal Hashing: Uses a family of hash functions to minimize collisions probabilistically.
    • Example: , where are random.

## In the real world

  1. eSewa (Nepal):
    • Uses hash tables to store user profiles (key: user ID, value: account details) for login verification.
    • Binary search optimizes sorted transaction histories for quick fraud detection.
0student1A1—2student3B3student2C4—
Hash Table for Student Grades (h(k) = last name mod 5)
  1. Khalti (Digital Payments):

    • Hashing secures passwords (stores hashed values, not plaintext).
    • Interpolation search approximates transaction amounts in ledgers for faster audits.
  2. Daraz (E-Commerce):

    • Binary search ranks product listings by price/sales for efficient filtering.
    • Hash tables cache frequently accessed items (e.g., "Best Sellers") to reduce database load.
  3. Ncell (Mobile Network):

    • Hashing maps phone numbers to user data in SIM databases for instant lookup.
    • Linear search (rarely) checks unsorted call logs for billing.
  4. NEPSE (Stock Exchange):

    • Binary search locates stock prices in sorted historical data for trend analysis.
    • Hash tables store real-time trades (symbol → price) for updates.

Worked Example (Ncell Billing):

  • Problem: Find the 10th highest call duration in a month’s logs (sorted: [5, 12, 15, 20, 22, 25, 30, 35, 40, 45, ...]).
  • Solution: Binary search to locate the 10th element in time.
    • Step 1: Mid = 5th element (22). Need higher → search right half.
    • Step 2: Mid = 8th element (35). Need lower → search left half.
    • Result: 10th element = 40 minutes.

3. Exam Tip

  1. Searching:

    • Binary search requires sorted data; interpolation search needs uniform distribution.
    • Derive time complexities from recurrence relations (e.g., → ).
  2. Hashing:

    • Load factor is critical: high → more collisions → degrade to .
    • Resizing: Always double the table size to keep efficient.
    • Collision resolution: Chaining is simpler; open addressing avoids pointers but risks clustering.
  3. Common Pitfalls:

    • Forgetting to resize the hash table (leads to operations).
    • Applying binary search on unsorted data (incorrect).
    • Ignoring worst-case scenarios (e.g., all keys hash to the same slot).
  4. Practical Questions:

    • Given a hash function , show collisions for keys [10, 17, 24].
    • Compare the time to search [1, 3, 5, 7] using linear vs. binary search.
    • Design a hash table for 1000 students with IDs 100–1099 (choose size and method).

Key Formulae to Memorize:

  1. Binary Search Midpoint: (avoids overflow).
  2. Load Factor: .
  3. Interpolation Search Position:

Based on the PU BE Computer (PU) syllabus for Data Structure and Algorithms (CMP160), unit 9.

Discussion

Loading…