A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/dsa/java-program-for-linear-search/ below:

Java Program for Linear Search

Java Program for Linear Search

Last Updated : 23 Jul, 2025

Try it on GfG Practice

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

Please refer to the complete article on Linear Search for more details.

Linear Search in Java

Example:

Java
// Java code for linearly search x in arr[]. If x
// is present then return its location, otherwise
// return -1
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

Time Complexity:

Space Complexity: O(1)



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4