Loading lessons...
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
keyata[n]before the loop so the loop only checkswhile (a[i] != key) i++;- eliminating thei < nbounds 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 & Conquer)
Requires a sorted array with O(1) random access (not suitable for singly linked lists!):
- Maintain bounds
low = 0, high = n - 1. - Compute
mid = low + (high - low) / 2(avoids integer overflow oflow + high). - If
a[mid] == key, returnmid. - If
key < a[mid], discard right half (high = mid - 1); else discard left half (low = mid + 1).
- Best Case: O(1) | Average & 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 < 50) →low = 4. - Step 2:
low=4, high=6, mid=5(a[5]=60 > 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
| Algorithm | Prerequisite | Time (Worst) | Space |
|---|---|---|---|
| Sequential Search | None (array or list) | O(n) | O(1) |
| Binary Search | Sorted array (random access) | O(log2 n) | O(1) iter / O(log n) rec |
| Interpolation Search | Sorted, uniformly distributed array | O(n) worst / O(log log n) avg | O(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]forkey = 50. (7.5 Marks) - Write: Prerequisite, time/space comparison table,
binarySearch()C code usinglow + (high - low)/2, and 3-steplow, high, midtrace. - Q2. What is Sentinel Sequential Search? How does it optimize standard Linear Search? (5 Marks)
- Write: Placing
keyat the end eliminates thei < nbounds check per iteration; includesentinelSearch()C code.