Open In App

Java Program for Linear Search

Last Updated : 09 Apr, 2025
Summarize
Comments
Improve
Suggest changes
Share
10 Likes
Like
Report

Linear Search is the simplest searching algorithm that checks each element sequentially until a match is found. It is good for unsorted arrays and small datasets.

Given an array a[] of n elements, write a function to search for a given element x in a[] and return the index of the element where it is present. If the element is not present in the array, then return -1.

Input/Output:

Input: a = [ 1, 2, 3, 5, 7], x = 3
Output = Element found at index: 2

Input a = [1, 2, 3, 5, 7] x = 8
Output = -1

Algorithm for Linear Search

  • Start 
  • Declare an array and search element as the 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 to the complete article on Linear Search for more details.

Linear Search in Java

Example:


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: O(1)


Next Article
Practice Tags :

Similar Reads