Linear Search
excerpt: This covers the building blocks such as Linear Scan, Value Comparison and Early Termination. tags: linearscan valuecomparison earlytermination traversingsequence
A linear search or exhaustive search loops through the items in the array, looking for the target item. The diagram shows a linear search for the value 77.
Linear search can work on linked lists, where it is not easy to jump from one part of the list to another, as you can in an array. Linear search also works on unsorted lists.
Linear Search in Unsorted List


Linear Search in Sorted List
But if the items are sorted, the search can stop if it finds an item with a value greater than the target value. The early stopping saves a little time if the target value is not in the list.


The search may check the entire array to conclude that an item is not there, so the worst case runtime is O(N). Even in the average case, the run time is O(N). The number of steps required to search for every item in the array is 1 + 2 + 3 + … + N = N * (N + 1) / 2. The average search time for all the N times is N * (N + 1) / 2 divided by N which is N + 1 / 2, this gives the average runtime of O(N).
Search in String


Traversing a sequence and returning when we find something we are looking for is called a search.
Building Blocks
 Linear Scan
 Value Comparison
 Early Termination
 Traversing Sequence