-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLinear Search 1
More file actions
29 lines (27 loc) · 789 Bytes
/
Linear Search 1
File metadata and controls
29 lines (27 loc) · 789 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
//Given an array of n element, find the given value in it using linear search
import java.util.*;
class Test{
static int linearSearch(int key, int arr[]){
for(int i=0; i<arr.length; i++){
if(arr[i]==key)
return i;
}
return -1;
}
public static void main(String args[]){
Scanner sc= new Scanner(System.in);
System.out.print("Enter the number of elements in the array: ");
int n=sc.nextInt();
System.out.print("Enter the elements in the array: ");
int a[]=new int [n];
for(int i=0; i<n; i++)
a[i]=sc.nextInt();
System.out.print("Enter the elements to search: ");
int key=sc.nextInt();
int result=linearSearch(key, a);
if(result ==-1)
System.out.print("Element NOT found");
else
System.out.print("Element found at index number "+result);
}
}