Searching for a value
Linear/Sequential Search
Linear Search is the act of looking through a collection from the start and determining the index of the value you are searching for.
Best Case Scenario: The first item is the target value
Average Case: The target is somewhere near the middle of the dataset
Worst Case: The target is not found, and you have analyzed every single value
By encountering the worst case scenario, we can potentially have a slow algorithm.
If the array had a million data points, and our target value is not one of the given value, the algorithm would be required to make a million comparisons to determine it is not in the array.
The study of efficiency of algorithm is called Complexity Analysis.
The search algorithm is called "linear" because it individually searches for the target from start to end.
Binary Search
Binary Search is a searching algorithm that works only on sorted and comparable dataset. It is considered to be significantly faster than linear search because it ignores where the target value cannot exist in the dataset by comparing the target with its generated midpoint.
The midpoint changes every iteration to shrink the search range within the dataset until the target is found or not found.
Linear vs Binary Search
As the dataset gets bigger, the linear search will do more comparisons compared to binary search. This classifies that binary search is a faster algorithm than linear search.
The weakness of binary search are the following:
The dataset must be sorted (which increases complexity if the dataset is not sorted)
The dataset must be comparable
The algorithm cannot be used to find multiple instances or duplicates; it can only generate a single answer
Connected Reading
Last updated