Pageviews

Saturday 24 August 2013

Linear search program in Java

by Unknown  |  in Source Codes at  Saturday, August 24, 2013

Linear search:It is one of the most simplest searching technique,in this search it is checked whether a given element is present in the list or not.Linear search compare each and every element of the list with the given value,if it is presented it is returned,else the list does not contains the element we are searching.

Java program code:

import java.util.Scanner;
class linear
{
public static void main(String args[]) 
{
int i,flag=0;
Scanner r=new Scanner(System.in);
System.out.println("Enter number of elements");
int n=r.nextInt();
System.out.println("Enter elements of the list");
int[] ar=new int[n];
for(i=0;i<ar.length;i++)
{
ar[i]=r.nextInt();
}
System.out.println("Enter the element you want to search");
int k=r.nextInt();
for(i=0;i<n;i++)
{
if(ar[i]==k)
{
flag=1;
break;
}
}
if(flag==1)
{
System.out.println("Item found at "+i+" location");
}
else
{
System.out.println("Item not found");
}
}


Output of the program:


Linear search


Advantages of Linear Search:


  • You need not to enter elements in sorted form.
  • It is the simplest searching technique.



Disadvantages of Linear Search:


  • This search is inefficient because it compares elements of the list with the searched element from start to end of the list,this method does not holds good if number of elements in the list are large.


0 comments:

Proudly Powered by Blogger.