1. Linear Search
Intuition
Traverse array from index 0 to n-1. If arr[i] == target, return i. Else return -1.
When to apply: When simplicity is preferred over performance on tiny arrays.
Algorithm
- Step 1: Iterate index i from 0 to n - 1.
- Step 2: If arr[i] == target, return i.
- Step 3: Return -1 if not found.
#include <iostream>#include <vector>#include <string>#include <algorithm>using namespace std; int searchNearlySorted(const vector<int>& arr, int target) { for (int i = 0; i < (int)arr.size(); ++i) { if (arr[i] == target) return i; } return -1;} int main() { // Sample driver execution cout << "Execution completed successfully." << endl; return 0;} Time & Space Complexity
- Time complexity:
O(n)— Checks all n elements sequentially. - Space complexity:
O(1)— Uses constant O(1) space.