Linear Search algorithm is one of the most easiest algorithms to understand in computer science with some of its advantages and disadavantages. One of the main drawbacks of Linear Search algorithm is that it is too much time-consuming for large datasets. Hence, in practical field other algorithms are preferred such as Binary Search algorithm or hashtables etc. which are efficient and powerful. One main advantage of Linear Search algorithm over Binary Search algorithm is that it can work with unsorted datasets or arrays.
Pseudocode for Linear Search Algorithm
for j = 0 to length (arr) -1 do if k = arr[j] then return true // In case value found return false
Let’s suppose we have an array arr with 6 elements,
arr[6] = {2, 6, 3, 5, 9, 8}
Now, we want to find k which is equal to 5. Here, we have two senarios that are needed to be considered,
1st Scenario
K is compared with each element of the array and if both elements are same then the algorithm returns true and terminates.
2nd Scenario
K is compared with each element of the array. If k is not equal to any element present in the array then the algorithm returns false and terminates.
Performance-wise, three different execution-time scenarios in Linear Search algorithm are as following,
Worst Case Execution Time
In worst case n number of comparisons are needed to find k. n is the number of elements present in the array.
Average Case Execution Time
In average case (n+1) / 2 comparisons are needed. n is the number of elements present in the array.
Best Case Execution Time
In best case only one comparison is needed. It means that the very first element of the array is equal to k.