Java Program for Linear Search
Last Updated :
23 Oct, 2024
Improve
Try it on GfG Practice
Given an array a[] of n elements, write a function to search a given element x in a[].
Algorithm for Linear Search
- Start
- Declare an array and search element as key.
- Traverse the array until the number is found.
- If the key element is found, return the index position of the array element
- If the key element is not found, return -1
- Stop.
Please refer complete article on Linear Search for more details!
Linear Search in Java
Below is the implementation of Linear Search in Java:
// Java code for linearly search x in arr[]. If x
// is present then return its location, otherwise
// return -1
class LinearSearch {
static int search(int a[], int n, int x)
{
for (int i = 0; i < n; i++) {
if (a[i] == x)
return i;
}
// return -1 if the element is not found
return -1;
}
public static void main(String[] args)
{
int[] a = { 3, 4, 1, 7, 5 };
int n = a.length;
int x = 4;
int index = search(a, 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: The best-case time complexity of the linear search is O(1).
Average Case Complexity: The average case time complexity of the linear search is O(n).
Worst-Case Complexity: The worst-case time complexity of the linear search is O(n).
Space Complexity:
Space complexity : O(1)


