Skip to content
SimpleScope

Searching

Linear search vs Binary search

Linear search and Binary search both find a value in an array, in different ways. Linear search: scan every element in order. Binary search: halve the range of a sorted array. In the worst case binary search takes O(log n) while linear search takes O(n), so binary search scales better on large inputs.

At a glance

PropertyLinear searchBinary search
TechniqueScan every element in orderHalve the range of a sorted array
Best case timeO(1)O(1)
Average case timeO(n)O(log n)
Worst case timeO(n)O(log n)
Extra spaceO(1)O(1)
Stable (equal values keep their order)Not applicableNot applicable
In place (no extra array)Not applicableNot applicable
Needs sorted inputNoYes

When to choose each

Choose linear search when

the data is unsorted, small, or searched only once.

Avoid it when

you search the same large array many times.

Choose binary search when

the array is sorted and you search it many times.

Avoid it when

the data is unsorted, or cannot be reached by index.

The same inputs, counted

These numbers come from running both real implementations: comparisons, on the sorted array 2, 5, 8, 12, 16, 23, 38.

InputLinear searchBinary search
Target is the first element15
Target in the middle41
Target is the last element75
Target is not in the array76

See them run