Basic Linear Search
A
technique used in computer science to locate an element in an
array is called sequential or linear search. It goes through the array
element by element until a match is found or all of the
elements have been searched. Get an array of Integers arr[] with size n and
element e to be found. Apply Linear
Search to find the element e in the array
arr[]. If element e is found, print
its index; if not, print -1.
Examples
Input
1:
5
5
7 9 3 1
9
Output
1:
2
Input
2:
5
5
7 9 3 1
4
Output
2:
-1
Try your Solution
Strongly recommended to Solve it on your own, Don't directly go to the solution given below.
Program or Solution
import java.util.*;
class SearchL
{
public static void main(String args[])
{
//Variable and Object Declarations
Scanner input = new Scanner(System.in);
int n,e,pos=-1;
//Getting size of Array & Declare Array arr[]
n = input.nextInt();
int arr[] = new int[n];
//Get n values to array arr[]
for(int i = 0; i<n; i++)
{
arr[i] = input.nextInt();
}
e = input.nextInt();
//Linear Search
for(int i = 0; i<n; i++)
{
if(arr[i]==e)
{
pos = i;
break;
}
}
System.out.print(pos);
}
}