File tree Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Original file line number Diff line number Diff line change
1
+ //Given an array of n element, find the given value in it using linear search
2
+
3
+ import java.util.*;
4
+ class Test{
5
+ static int linearSearch(int key, int arr[]){
6
+ for(int i=0; i<arr.length; i++){
7
+ if(arr[i]==key)
8
+ return i;
9
+ }
10
+ return -1;
11
+ }
12
+
13
+ public static void main(String args[]){
14
+ Scanner sc= new Scanner(System.in);
15
+ System.out.print("Enter the number of elements in the array: ");
16
+ int n=sc.nextInt();
17
+ System.out.print("Enter the elements in the array: ");
18
+ int a[]=new int [n];
19
+ for(int i=0; i<n; i++)
20
+ a[i]=sc.nextInt();
21
+ System.out.print("Enter the elements to search: ");
22
+ int key=sc.nextInt();
23
+ int result=linearSearch(key, a);
24
+ if(result ==-1)
25
+ System.out.print("Element NOT found");
26
+ else
27
+ System.out.print("Element found at index number "+result);
28
+ }
29
+ }
You can’t perform that action at this time.
0 commit comments