Linear Search is a search technique, in which the key to be searched is compared with each element in the list, until it is found. This technique works even if the list is not sorted. It is considered to be slower than binary search as the size of the input (list) grows.
Below is the code written in Java that demonstrates linear search:
import java.io.*;
class LinearSearch{
public static void main(String args[])throws IOException{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
int a[]={92, 34, 78, 12, 45, 7, 81, 60, 51, 10};
int key, i;
System.out.print("Enter the integer to search:");
key=Integer.parseInt(br.readLine());
for(i=0;i<a.length;i++){
if(key==a[i])
break;
}
if(i==10)
System.out.println(key+" not found");
else
System.out.println(key+" found at index "+i);
}
}
No comments:
Post a Comment