Searching / Beginner
Linear Search Visualizer
Check every value from left to right until you find the target or run out of values.
Start the Linear Search simulation → Step forward and back, change the input, follow the code line by line in Java, Python, C++, C or JavaScript. Free, no sign-up.
Time and space complexity
| Best time | O(1) |
|---|---|
| Average time | O(n) |
| Worst time | O(n) |
| Extra space | O(1) |
Worked example, step by step
The same steps the simulator shows, on a small input.
- Look for 63 by checking each value from the left.
[3, 8, 15, 23, 42, 51, 63, 77, 90] - Is a[0] = 3 equal to 63? No.
- Is a[1] = 8 equal to 63? No.
- Is a[2] = 15 equal to 63? No.
- Is a[3] = 23 equal to 63? No.
- Is a[4] = 42 equal to 63? No.
- Is a[5] = 51 equal to 63? No.
- a[6] is 63. Found it after 7 checks. Return 6.
Linear search in Java, Python, C++, C and JavaScript
int linearSearch(int[] a, int target) {
for (int i = 0; i < a.length; i++) {
if (a[i] == target) return i;
}
return -1;
}
def linear_search(a, target):
for i in range(len(a)):
if a[i] == target:
return i
return -1
int linearSearch(const vector<int>& a, int target) {
for (int i = 0; i < (int)a.size(); i++) {
if (a[i] == target) return i;
}
return -1;
}
int linearSearch(int a[], int n, int target) {
for (int i = 0; i < n; i++) {
if (a[i] == target) return i;
}
return -1;
}
function linearSearch(a, target) {
for (let i = 0; i < a.length; i++) {
if (a[i] === target) return i;
}
return -1;
}In an interview
It works on any array, sorted or not. If the array is sorted, binary search is the better answer.