Searching is the cornerstone of efficient data retrieval. From linear scanning of unorganized lists to logarithmic binary division, choosing the right search algorithm determines system responsiveness and algorithmic scalability.
Searching algorithms allow developers to locate specific target values within data structures efficiently. In this chapter, we explore Linear Search and Binary Search.
01. Linear Search
Linear Search is a sequential search algorithm that starts at the beginning of a collection and checks every element until the target item is found or the end of the array is reached.
Complexity
| Metric | Complexity | Description |
|---|---|---|
| Best Time | Target is at index 0. | |
| Average Time | Target is located in the middle. | |
| Worst Time | Target is at index or absent. | |
| Space | In-place operation. |
02. Binary Search
Binary Search is a logarithmic divide-and-conquer search algorithm that operates on pre-sorted arrays. It repeatedly compares the target value to the middle element of the array, discarding half of the search space with every iteration.
Complexity
| Metric | Complexity | Description |
|---|---|---|
| Best Time | Target is at the initial middle index. | |
| Average Time | Search space halves on every step. | |
| Worst Time | Target found at the deepest level. | |
| Space | Iterative implementation. |
C++ Implementation
1#include <vector>23int binarySearch(const std::vector<int>& arr, int target) {4 int low = 0;5 int high = arr.size() - 1;67 while (low <= high) {8 int mid = low + (high - low) / 2;910 if (arr[mid] == target) return mid;11 if (arr[mid] < target) low = mid + 1;12 else high = mid - 1;13 }14 return -1;15}
Summary
- Use Linear Search when data is unsorted or small ().
- Use Binary Search when data is sorted and fast logarithmic lookup () is required.