Linear Search in Java

What is Linear Search?

Linear search or sequential search is a method for finding a particular value in a list that checks each element in sequence until the desired element is found or the list is exhausted.

Its worst case cost is proportional to the number of elements in the list. Its expected cost is also proportional to the number of elements if all elements are searched equally. If the list has more than a few elements and is searched often, then more complicated search methods such as binary search is used.

 

Program to implement Linear Search in Java:

import java.util.Scanner;

class LinearSearch
{
    public static void main(String args[])
    {
        int c, n, search, array[];

        Scanner in = new Scanner(System.in);
        System.out.println("Enter number of elements");
        n = in.nextInt();
        array = new int[n];

        System.out.println("Enter " + n + " integers");

        for (c = 0; c < n; c++)
        array[c] = in.nextInt();

        System.out.println("Enter value to find");
        search = in.nextInt();

        for (c = 0; c < n; c++)
        {
            if (array[c] == search) /* Searching element is present */
            {
                System.out.println(search + " is present at location " + (c + 1) + ".");
                break;
            }
        }
        if (c == n) /* Searching element is absent */
        System.out.println(search + " is not present in array.");
    }
}

Output:

 

$ java LinearSearch
 Enter number of elements
 5
 Enter 5 integers
 34
 99
 524
 -32
 8
 Enter value to find
 99
 99 is present at location 2.

 

Leave a Reply