Linear search — O(n)
referencebeginnerLinear search checks every element in order until it finds the target or runs out of elements — O(n), and the only option when the data is not sorted.
What we're doing: Find the index of a target value by checking each element in order.
- 3
- Every element is compared, in order — there is no way to skip ahead without knowing the data is sorted.
- 4
- The function returns the moment it finds a match; it never needs to look at the rest.
3
-1Why this works: 7 sits at index 3, so the loop returns as soon as it gets there. 5 never appears, so the loop runs to the end and returns -1.
Remember: Reach for linear search when the data is not sorted, or when you will only search it once — binary search only pays off once the data is sorted and searched repeatedly.