Linear Search Array in Java

Linear search is very simple and easy technique to search from an array. In this problem we added elements, saved it in a array and then apply linear search for searching an element within array.

Source Code 


import java.util.Scanner;
classLinearSearch
{
  public static void main(String args[])
  {
    int arr;
    int search;
    int number;
    int array[];
    Scanner in = new Scanner(System.in);
    System.out.println("How Many Elements :");
    number = in.nextInt();
    array = new int[number+1];
    for (arr = 1; arr < number+1 ; arr++)
    {
        System.out.println("Enter " + arr + "");
        array[arr] = in.nextInt();
    }
    System.out.println("Enter value to find");
    search = in.nextInt();

    for (arr = 0; arr < number; arr++)
    {
      if (array[arr] == search)    
      {
         System.out.println(search + " Present at Index  " + (arr) + ".");
          break;
      }
   }
   if (arr == number) 
      System.out.println(search + "Invalid Input ! ");
  }

}

Output of the Program 


Java Searching Mechanism
Linear Search in Java

Share on Google Plus

About Asad

Asad Niazi is Software Engineer , Programmer, Web Developer and a young mentor of BloggersTown and PProgramming. Asad Love to writes about Technology, Programming, Blogging and make money online.

2 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. I got answer of my interview question.
    Thanks a lot for clearing my idea.

    ReplyDelete