Linear search is a simple search algorithm that involves examining each element of a list or array sequentially until the desired element is found or it is determined that the element is not present. To perform a linear search, you can follow these steps:
Algorithm:
- Set a variable low to the first index of the list or array.
- Set a variable high to the last index of the list or array.
- Set a variable found to False.
- Set a variable i to low.
- While i is less than or equal to high and found is False:
- If the element at index i is equal to the desired element, set found to True.
- Otherwise, increment i by 1.
- If found is True, return the index i. Otherwise, return -1 to indicate that the element was not found.
Linear search has a time complexity of O(n), where n is the number of elements in the list or array. This means that the time it takes to perform the search increases linearly with the size of the list or array. As a result, the linear search may not be the most efficient algorithm for searching large lists or arrays. However, it can be useful for small lists or arrays or when the elements are not sorted.