1. Linear Traversal
Intuition
Start at index 0 and increment index by 1 until arr[i] == target (return i) or arr[i] > target (return -1).
When to apply: When index p is guaranteed to be extremely small.
Algorithm
- Step 1: Set i = 0.
- Step 2: While arr[i] <= target, if arr[i] == target return i; else i++.
- Step 3: Return -1.
#include <iostream>#include <vector>#include <string>#include <algorithm>using namespace std; int searchInfinite(const vector<int>& arr, int target) { int i = 0; while (arr[i] <= target) { if (arr[i] == target) return i; i++; } return -1;} int main() { // Sample driver execution cout << "Execution completed successfully." << endl; return 0;} Time & Space Complexity
- Time complexity:
O(p)— Takes p steps where p is the index of target. - Space complexity:
O(1)— Only constant extra space.