← All resources

Linear Search in Array

Java program for linear search: Linear search is very simple, To check if an element is present in the given list we compare search element with every element in the list. If the number is found then success occurs otherwise the list doesn’t contain the element we are searching.

Wikipedia – Linear Search

import java.io.*;
public class LinearSearch
{
    public static void main()throws IOException
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n;      //To store the size of the array
        System.out.println("Enter the size of the array: ");
        n = Integer.parseInt(br.readLine());
        int a[] = new int[n], i, s, pos=-1;
        //input the array
        System.out.println("Enter "+n+" values for the array: ");
        for(i=0;i<n;i++)
        {
            a[i] = Integer.parseInt(br.readLine());
        }
        System.out.println("Input the value to search: ");
        s = Integer.parseInt(br.readLine());

        //Performing linear search
        for(i=0;i<n;i++)
        {
            if(s==a[i])
            {
                pos=i+1;        //Value of pos changes only when s==a[i]
                break;
            }
        }
        if(pos!=-1)
            System.out.println("Value is present at position: "+pos);
        else
            System.out.println("Value is not present");
    }
}