Java Program for Linear Search

Last Updated : 18 Aug, 2026

Linear Search is a simple searching algorithm that checks each element of an array sequentially until the required element is found or all elements have been checked. It is useful for small or unsorted arrays because the elements do not need to be arranged in any particular order.

  • Stops when the required element is found.
  • Returns the index of the found element.

Illustration

Given an array a[] and a search element x, the program returns the index of x if it is present. If the element is not found, it returns -1.

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

Try It Yourself
redirect icon
Linear-search-algorithm-1
  • Start.
  • Declare an array and the element to be searched.
  • Traverse the array from the first element to the last.
  • Compare each element with the search element.
  • If a match is found, return its index.
  • If no match is found, return -1.
  • Stop.

Example: Linear Search program in Java

Java
class Geeks
{

  	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 index: " + index);
    }
}

Output
Element found at position 1

Explanation: The search() method checks each element of the array from left to right. When it finds 4 at index 1, it immediately returns that index. If the loop finishes without finding the element, the method returns -1.

  • Simple and easy to implement.
  • Works with both sorted and unsorted arrays.
  • Does not require additional memory.
  • Suitable for small datasets.
  • Can be used when elements are not arranged in sorted order.
Comment