Start from the first element, check each one for the target. If found, return index. If end reached without finding, return -1.
Execution Sample
DSA Javascript
function linearSearch(arr, target) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === target) return i;
}
return -1;
}
Searches array elements one by one to find the target value and returns its index or -1 if not found.
Execution Table
Step
Operation
Index Checked
Element at Index
Is Element == Target?
Action
Result
1
Check element
0
3
No
Move to next index
Continue searching
2
Check element
1
5
No
Move to next index
Continue searching
3
Check element
2
7
Yes
Return index 2
Found target at index 2
4
End
-
-
-
-
Search stops
💡 Target found at index 2, so search stops early.
Variable Tracker
Variable
Start
After Step 1
After Step 2
After Step 3
Final
i
0
1
2
-
2
arr[i]
3
5
7
-
7
Result
undefined
undefined
2
-
2
Key Moments - 3 Insights
Why does the search stop immediately when the target is found?
Because in step 3 of the execution_table, the condition 'arr[i] === target' is true, so the function returns the index immediately without checking further elements.
What happens if the target is not in the array?
The loop runs through all elements without finding the target, then returns -1 after the loop ends, as shown by the exit_note explaining search stops only when target is found or array ends.
Why do we check 'i < arr.length' in the loop?
To avoid checking outside the array bounds, ensuring we only check valid elements. This is implied in the concept_flow where we move to next index until the end is reached.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'i' when the target is found?
A2
B1
C0
D3
💡 Hint
Check the 'Index Checked' column in step 3 where the target is found.
At which step does the search stop because the target is found?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at the 'Action' column where the function returns the index.
If the target was 10 (not in array), what would the final result be?
AIndex 2
B-1
CIndex 0
DUndefined
💡 Hint
Refer to the exit_note and key_moments about what happens when target is not found.
Concept Snapshot
Linear Search Algorithm:
- Start from first element
- Check each element one by one
- If element == target, return index
- If end reached without finding, return -1
- Simple but can be slow for large arrays
Full Transcript
Linear Search checks each element in the array from start to end. It compares each element with the target value. If it finds the target, it returns the index immediately. If it reaches the end without finding the target, it returns -1. This method is simple and works on any list but can be slow if the list is long because it may check every element.