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 indexThe position of a piece of data in a list. needed to perform a binary search.
Linear v binary search example
Both algorithmA sequence of logical instructions for carrying out a task. In computing, algorithms are needed to design computer programs. 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 trace tableUsed when testing a program to record changes in variable values as code executes., this would look like:
Linear search trace table
Search term
Index
Data
Found
List
7
1
1
False
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
2
2
False
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
3
3
False
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
4
4
False
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
5
5
False
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
6
6
False
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
7
7
True
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Search term
7
Index
1
Data
1
Found
False
List
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Search term
Index
2
Data
2
Found
False
List
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Search term
Index
3
Data
3
Found
False
List
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Search term
Index
4
Data
4
Found
False
List
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Search term
Index
5
Data
5
Found
False
List
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Search term
Index
6
Data
6
Found
False
List
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Search term
Index
7
Data
7
Found
True
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.