C/C++ Program for Linear Search
Problem: Given an array arr of n elements, write a function to search a given element x in arr.
Step 1: Start
Step 2: Declare an array, and search data variable-x.
Step 3: Traverse the entire array until search data is found.
If search data is present then
return its location
Step 4: print data
Step 5: Stop
PROCEDURE LINEAR_SEARCH (LIST, VALUE) FOR EACH ITEM IN THE LIST IF SEARCH ITEM == VALUE RETURN THE ITEM'S LOCATION ELSE RETURN -1 END FOR END PROCEDURE
Element found at position 1
The time complexity of the above algorithm is O(n).
BEST CASE COMPLEXITY
The best-case time complexity – O(1).
when the search element is present at the first location of the array it will return the search data location and will terminate the loop and the best case occur. So the best-case time complexity of the linear search is o(1).
AVERAGE CASE COMPLEXITY
when the search element is present at the random location of the array then the array will traverse until search data is found.
The average case time complexity – O(n).
when the search element is present at the last location of the array then the worst case occurs So the worst-case time complexity of the linear search is o(1).
The worst-case time complexity – O(n)
The space complexity of the linear search is o(n) cause it takes no extra space to store data.
Please refer complete article on Linear Search for more details!
Please Login to comment...