Searching for a value

PSEUDOCODE

Let L represent an array of values
    Let n represent the size of the array
Let T represnet target value T, 
Let i represent index of L

1. Set i to 0.
2. If L[i] = T, the search terminates successfully; return i.
3. If i < n, Increase i by 1 and go to step 2. 
4. If i == n, the search terminates unsuccessfully.

Linear Searcharrow-up-right 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.

circle-info

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 Analysisarrow-up-right.

The search algorithm is called "linear" because it individually searches for the target from start to end.

Binary Searcharrow-up-right 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.

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

  • Linear Search (Link)

  • Binary Search (Link)

  • Big-O Notation (Link)

Last updated