Java linear search program

Java linear search program

Java linear search program

Linear search is a very simple search algorithm. In this type of search, a sequential search is done for all items one by one. Every item is checked and if a match is found then that particular item is returned, otherwise the search continues till the end of the data collection.

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)  /* Element to search isn't present */
      System.out.println(search + " isn't present in array.");
  }
}

Program Output:

Enter number of elements
7
Enter 7 integers
1997
2000
2020
960
425
741
651
Enter value to find
1997
1997 is present at location 1.

I hope this post helps you to understand Linear search and its implementation in Java programming language.

Keep coding 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *