Algorithms
Linear Search
O(n) time — in the worst case, you check every item · O(1) space.
The idea, in plain English
Linear search checks every seat in a theater, one by one, to find your friend. It is simple and always works, even when the seats are in no particular order. You just look at each seat until you find your friend, or run out of seats.
How it works
- 1Start at the first item in the list.
- 2Compare it to what you are looking for. If it matches, you are done — return its position.
- 3If it does not match, move to the next item. If you reach the end, the item is not there.
When you'd use it
Use it for small lists, or unsorted data where you cannot do anything smarter. It is the fallback method that always works.
Common beginner mistakes
- Returning too early, or forgetting to return -1 when you do not find the item.
- Using it on huge sorted lists, where binary search would be far faster.
Try it — edit and run
Click the code to edit · press ⌘/Ctrl+↵ to run
Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.
Expected output — hit Run to try it
Index of 16: 3
Index of 99: -1See it in motion
Watch it searchLinear searchTarget 23O(n) time — in the worst case, you check every item · O(1) space.
Ready. Press play to hunt for the target.
0
Comparisons
—
Result
0/7
Step
0.0s
Time
CheckingIn rangeRuled outFound
Not sure this is the right topic? See the learning paths → or where this leads →