Skip to content

Commit f3b97bb

Browse files
authored
Create Linear Search 1
1 parent 8ee54ef commit f3b97bb

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

Linear Search 1

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
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+
}

0 commit comments

Comments
 (0)