大象传媒

Comparing linear and binary searches

Although linear and binary searching produces the same overall results, linear search is best used when the data is not in order, or for smaller lists. However, when the list is much longer and the data is in order, it is far more efficient to calculate the needed to perform a binary search.

Linear v binary search example

Both could be used to search the following list for the number 7:

1, 2, 3, 4, 5, 6, 7, 8, 9, 10

Linear search would require eight steps to find the search term in the list.

In a , this would look like:

Linear search trace table

Search termIndexDataFoundList
711False[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
22False[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
33False[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
44False[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
55False[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
66False[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
77True[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Search term7
Index1
Data1
FoundFalse
List[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Search term
Index2
Data2
FoundFalse
List[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Search term
Index3
Data3
FoundFalse
List[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Search term
Index4
Data4
FoundFalse
List[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Search term
Index5
Data5
FoundFalse
List[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Search term
Index6
Data6
FoundFalse
List[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Search term
Index7
Data7
FoundTrue
List[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

In contrast, binary search would take just four steps to find the same number.

In a trace table, this would look like:

Binary search trace table

Search termStartIndexDataFoundList
71105False[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
6108False[6, 7, 8, 9, 10]
676False[6, 7]
777True[7]
Search term7
Start1
Index10
Data5
FoundFalse
List[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Search term
Start6
Index10
Data8
FoundFalse
List[6, 7, 8, 9, 10]
Search term
Start6
Index7
Data6
FoundFalse
List[6, 7]
Search term
Start7
Index7
Data7
FoundTrue
List[7]