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[].
ALGORITHM :
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
else
return -1
Step 4: print data
Step 5: Stop
Pseudocode :
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
C/C++
C++
#include <bits/stdc++.h> using namespace std; // Linearly search x in arr[]. If x is present then return // its location, otherwise return -1 int search( int arr[], int n, int x) { int i; for (i = 0; i < n; i++) if (arr[i] == x) return i; return -1; } // Driver code int main() { int arr[] = { 3, 4, 1, 7, 5 }; int n = sizeof (arr) / sizeof (arr[0]); int x = 4; int index = search(arr, n, x); if (index == -1) cout << "Element is not present in the array" ; else cout << "Element found at position " << index; return 0; } |
Output:
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).
WORST-CASE COMPLEXITY
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)
SPACE COMPLEXITY:
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...