Linear searching in Java.

LINEAR SEARCHING IN JAVA.




                                                          Linear searching in JAVA ; This is simple java program that will search number array and try to find our desired number . This is called linear search because elements of  array are searched one - by -one and when our required element found array execution stops there. Linear searching is time taking process.




JAVA CODE :) 




import java.util.Scanner;


public class LinearSearch


{


  public static void main(String[]  args)


{


int n,x,i;


Scanner sc=new Scanner(System.in);


System.out.print("Enter array size:");


n=sc.nextInt();


int a[]=new int[n];


System.out.println("Enter "+n+" elements in Array:");


for(i=0;i<n;i++)


{


   a[i] = sc.nextInt();


}


System.out.print("Enter number you want to search:");


x=sc.nextInt();


sc.close();


for(i=0;i<n;i++)


{


   if(a[i]==x)


   {


     System.out.println("Your Enterd number is found at position:"+(i+1));


     break;


   }


}


   if(i==n)


   {


     System.out.println("Your Enterd number is not found:");


   }


}


}



 Input and Output :)






Post a Comment

0 Comments