Saturday 30 July 2016

Linear search

 Linear search
import java.lang.*;
import java.util.*;
import java.io.*;
class Search
{
public int linearsearch(int[]a,int key)
{
int flag=1;
for(int i=0;i<a.length;i++)
{
if(a[i]==key)
{
flag=0;
}
}
return(flag);
}
}
class Linearsearch
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
{
Search s=new Search( );
int []a;
int i,k,n,ch;
int f=1;
System.out.println("Linear Search\n");
System.out.println("Enter the size of array");
n=sc.nextInt( );
a=new int[n];
System.out.println("enter the elements");
for (i=0;i<n;i++)
a[i]=sc.nextInt( );
System.out.println("enter the element to search");
k=sc.nextInt( );
f=s.linearsearch(a,k);
if(f==0)
System.out.println("The element is found");
else
System.out.println("Element is not found");
}
}
}


Output:
javac Linearsearch.java
java Linearsearch
LINEAR SEARCH
Enter your choice
Enter the size of array
5
Enter the elements into the array
2
4
1
8
9
Enter the element to search
8
The element is found
Output:
javac Linearsearch.java
java Linearsearch
LINEAR SEARCH
Enter your choice
Enter the size of array
5
Enter the elements into the array
2
4
1
8
9
Enter the element to search
10
The element not found