Skip to main content

Program in Java Linear Search

Program in Java to implement Linear Search Algorithm


import java.util.Scanner;
class LinearSearch
{
 public static void main(String args[])
 {
  Scanner sc = new Scanner(System.in);
  System.out.println("Enter the number of elements: ");
  int n = sc.nextInt();
  int A[] = new int[n]; //array initialized
  System.out.println("Enter the values into the array: ");
  for(int i=0;i<n;i++)
  {
   A[i]=sc.nextInt(); //accepting the values into the array
  }
  System.out.println("Enter the value you want to find: ");
  int v = sc.nextInt();
  int pos=-1; //to store the index position of the value present in the array
  int flag=0; //flag value when 0 indicates the search value is not found
  //flag value when 1 indicates the search value is found
  for(int i=0;i<n;i++)
  {
   if(A[i]==v) //A[i] is compared to the value of v
   {
   //when value of v is found in the array
    pos=i; //store index of the array in position variable
    flag=1; //flag is set to 1 as the value is found
    break; //as soon as the value is found, the loop is stopped
   }
  }
  if(flag==1) //checking if the value of flag is 1
  {
   System.out.println(v+" is found at index "+pos);
  }
  else
  {
   System.out.println("Value not found");
  }
  
 }
}

Popular posts from this blog