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 element as key.
Step 3: Traverse the array until the number is found.
Step 4: If the key element is found, return the index position of the array element
Step 5: If the key element is not found, return -1
Step 6: Stop.
Pseudocode :
PROCEDURE LINEAR_SEARCH (LIST, VALUE)
FOR EACH ITEM IN THE LIST
IF SAME ITEM == VALUE
RETURN THE ITEM’S LOCATION
END IF
END FOR
END PROCEDURE
Java
class LinearSearch {
static int search( int arr[], int n, int x)
{
for ( int i = 0 ; i < n; i++) {
if (arr[i] == x)
return i;
}
return - 1 ;
}
public static void main(String[] args)
{
int [] arr = { 3 , 4 , 1 , 7 , 5 };
int n = arr.length;
int x = 4 ;
int index = search(arr, n, x);
if (index == - 1 )
System.out.println( "Element is not present in the array" );
else
System.out.println( "Element found at position " + index);
}
}
|
Output:
Element found at position 1
Time Complexity :
BEST CASE COMPLEXITY
In linear search, the best-case occurs when the search element is present at the first location of the array. So the best-case time complexity of the linear search is o(1).
The best-case time complexity of the linear search is o(1).
AVERAGE CASE COMPLEXITY
In linear search average case occurs when the search element is present at the random location of the array.so the average case time complexity of the linear search is o(1).
The average case time complexity of the linear search is o(n).
WORST-CASE COMPLEXITY
In linear search, the worst case occurs when the search element is present at the last location of the array So the worst-case time complexity of the linear search is o(1).In the worst case in if the search element is not present in the given array then we need to traverse the entire array to search element. So the worst-case time complexity of the linear search is o(n).
The worst-case time complexity of the linear search is o(n)
SPACE COMPLEXITY:
The SPACE complexity of the linear search is o(1)
Linear Search Applications
we use linear search in following things:
• for search item in the smaller array.
• For fast searching
The time complexity of the above algorithm is O(n). Please refer complete article on Linear Search for more details!
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
05 Jun, 2022
Like Article
Save Article