Linear Search
Last updated
Last updated
Linear Search, also known as Sequential Search, is one of the simplest and most intuitive searching algorithms. It involves scanning an array or list of elements one by one until the target element is found or the entire array is traversed. Linear Search is applicable to both sorted and unsorted arrays.
The logic behind Linear Search is straightforward:
Start from the first element (index 0) of the array.
Compare the current element with the target element.
If the current element matches the target element, return its index (position) in the array.
If the current element does not match, move to the next element in the array and repeat steps 2 and 3.
Continue this process until the target element is found or the end of the array is reached (no match found).
Both of these implementations perform a linear search on the given array and return the index of the target element if found, or -1 if the element is not present in the array. You can replace the arr
and target
values with your own data to test the Linear Search algorithm with different inputs.
The time complexity of Linear Search can be analyzed mathematically as follows:
Let n be the number of elements in the array.
In the worst-case scenario, Linear Search needs to compare the target element with each element in the array until it either finds a match or reaches the end of the array. Therefore, in the worst case:
The first comparison takes 1 operation (comparing the target with the first element).
The second comparison takes 2 operations (comparing the target with the second element).
The k-th comparison takes k operations.
In the worst case, the target element is either found at the last position in the array or is not present in the array, which means we perform n comparisons.
To calculate the total number of operations (comparisons) in the worst case, we can sum the operations from 1 to n:
Therefore, the worst-case time complexity of Linear Search is:
When we analyze time complexity, we are interested in how the algorithm's performance scales with the size of the input (in this case, the number of elements in the array). In big O notation, we simplify this to:
So, the time complexity of Linear Search is O(n) in the worst case. This means that the number of operations performed by Linear Search grows linearly with the size of the input array. It is a simple but not very efficient searching algorithm, especially for large datasets, where more efficient algorithms like Binary Search or Hashing are preferred.
While Linear Search is not the most efficient algorithm for large datasets, it remains a fundamental concept and serves as the basis for understanding more complex searching algorithms.