← Back

Linear Search

simpleunsorted
Press play to start
1function linearSearch(arr: number[], target: number): number {
2 for (let i = 0; i < arr.length; i++) {
3 if (arr[i] === target) return i;
4 }
5 return -1;
6}
Step 1/0
Custom array:

Complexity

Best:O(1)
Average:O(n)
Worst:O(n)
Space:O(1)

Description

Sequentially checks each element until the target is found or the array ends. Works on both sorted and unsorted arrays.

When to use

Simple O(n) search for small or unsorted arrays. Best when you only search occasionally and the list is short.