Sunday, August 28, 2011

Java Program to Perform Linear Search

Linear Search is a Sequential Searching algorithm, it is commonly used to find an element in an array.It works by checking whether each element in the array is equal to the element to be found.This done by Incrementing the Index of the array.If the element is found a flag variable is set to indicate the presence of the element and the index of the array ,where the element is found is reported.The Complete Source Code to implement Linear Search in java is provided below.
 import java.io.*;  
 import java.lang.*;  
 class Linear  
 {  
 DataInputStream get;  
 int a[];  
 int key,n,i;  
 void getdata()  
 {  
  try  
  {  
   get=new DataInputStream(System.in);  
   System.out.println("Enter the size");  
   n=Integer.parseInt(get.readLine());  
   a=new int[n];  
   System.out.println("Enter the elements");  
   for(i=0;i<n;i++)  
   a[i]=Integer.parseInt(get.readLine());  
   System.out.println("Enter the key element");  
   key=Integer.parseInt(get.readLine());  
  }  
  catch(Exception e)  
  {  
   System.out.println(e.getMessage());  
  }  
 }  
 void search()  
 {  
 int flag=0,j,i;  
 int pos[]=new int[10];  
 for(i=0,j=0;i<n;i++)  
  {  
  if(key==a[i])  
  {  
   flag=1;  
   pos[j]=i+1;  
   j++;  
  }  
  }  
 if (flag==1)  
 {  
  System.out.println("Element is found in position:");  
  for(i=0;i<j;i++)  
  System.out.print(pos[i]+" ");  
 }  
 else  
  System.out.println("Element not present in this array");  
 }  
 }  
 class Linearsearch  
 {  
 public static void main(String arg[])  
 {  
  Linear obj=new Linear();  
  obj.getdata();  
  obj.search();  
 }  
 }  

No comments:

Post a Comment

Which is the Best Photo Watermarking Software

Photo Theft is becoming more and more common in the web with the outburst of social websites like Facebook,Google Plus and Image sharing se...