Searching means to find whether a particular value is present in the array or not. The simplest form of search is the linear search also called sequential search. This technique is meant for searching a particular item in an unsorted data set in a sequential manner until the desired item is found. It works by comparing every element of the array one by one in sequence until a match is found.
Here is an example, how a linear search work to find element (key) 12.
In the above example, the element was found at index number 5. The search algorithm returns the index number where the element found. If the element is not found at any index in the given array, then the search is said to be unsuccessful.
Linear Search Java Program
import java.util.scanner;
class LinearSearch
{
public static void main(String args[])
{
int i, n, key, a[];
Scanner scr=new Scanner(System.in);
System.out.println(" Enter number of elements");
n=scr.nextInt();
a=new int[n];
System.out.println(" enter" +n+ "integers");
for(i=0;i
a[i]=scr.nextInt();
System.out.println(" enter value to search");
key=scr.nextInt();
for(i=o;i
{
if(a[i]==key)
{
System.out.println(key+" is present at location"+(i+1));
break;
}
}
if(i==n)
{
System.out.println(" search is unsuccessful");
}
}
}
0 comments :
Post a Comment
Note: only a member of this blog may post a comment.