Lesson 22 +25 XP

Searching Algorithms: Sequential & Binary Search

Searching Algorithms: Sequential & Binary Search

Searching is the operation of locating a target record with key K in a collection of n records (returning its index/pointer on success, or -1/NULL on failure).

1. Sequential (Linear) Search & Sentinel Optimization

Inspects elements sequentially from index 0 to n - 1:

  • Applicability: Works on both sorted and unsorted arrays as well as linked lists.
  • Best Case: 1 comparison - O(1) (target at index 0).
  • Average Case (successful): (n + 1 / 2) comparisons - O(n).
  • Worst / Unsuccessful Case: n comparisons - O(n).
  • Sentinel Optimization: Place key at a[n] before the loop so the loop only checks while (a[i] != key) i++; - eliminating the i < n bounds check on every iteration!
C
int sentinelSearch(int a[], int n, int key) {
    int last = a[n - 1];
    a[n - 1] = key;
    int i = 0;
    while (a[i] != key) i++;
    a[n - 1] = last;
    if (i < n - 1 || a[n - 1] == key) return i;
    return -1;
}

2. Binary Search (Divide &amp; Conquer)

Requires a sorted array with O(1) random access (not suitable for singly linked lists!):

  1. Maintain bounds low = 0, high = n - 1.
  2. Compute mid = low + (high - low) / 2 (avoids integer overflow of low + high).
  3. If a[mid] == key, return mid.
  4. If key &lt; a[mid], discard right half (high = mid - 1); else discard left half (low = mid + 1).
  • Best Case: O(1) | Average &amp; Worst Case: O(log2 n) (at most ⌊ log2 n ⌋ + 1 comparisons-e.g., at most 20 comparisons for 1 million items!).

Worked Trace: Search key = 50 in [10, 20, 30, 40, 50, 60, 70]:

  • Step 1: low=0, high=6, mid=3 (a[3]=40 &lt; 50) → low = 4.
  • Step 2: low=4, high=6, mid=5 (a[5]=60 &gt; 50) → high = 4.
  • Step 3: low=4, high=4, mid=4 (a[4]=50 == 50) → Found at index 4!
C
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;
        if (key < a[mid]) high = mid - 1;
        else low = mid + 1;
    }
    return -1;
}

3. Search Algorithm Comparison

AlgorithmPrerequisiteTime (Worst)Space
Sequential SearchNone (array or list)O(n)O(1)
Binary SearchSorted array (random access)O(log2 n)O(1) iter / O(log n) rec
Interpolation SearchSorted, uniformly distributed arrayO(n) worst / O(log log n) avgO(1)
🎯 END-TERM EXAM PREP

📝 IPU End-Term Exam Corner (5-10 Marks)

  • Q1. Differentiate between Sequential Search and Binary Search. Write C code for Binary Search and trace it on [10,20,30,40,50,60,70] for key = 50. (7.5 Marks)
  • Write: Prerequisite, time/space comparison table, binarySearch() C code using low + (high - low)/2, and 3-step low, high, mid trace.
  • Q2. What is Sentinel Sequential Search? How does it optimize standard Linear Search? (5 Marks)
  • Write: Placing key at the end eliminates the i &lt; n bounds check per iteration; include sentinelSearch() C code.