This repository was archived by the owner on Jun 2, 2024. It is now read-only.
File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed
Java/Algorithm/SearchingAlgorithm Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
1
+ import java .util .Scanner ;
2
+
3
+ public class LinearSearch {
4
+
5
+ // Function to perform linear search
6
+ public static int linearSearch (int [] arr , int key ) {
7
+ for (int i = 0 ; i < arr .length ; i ++) {
8
+ if (arr [i ] == key ) {
9
+ return i ; // Return the index if key is found
10
+ }
11
+ }
12
+ return -1 ; // Return -1 if key is not found
13
+ }
14
+
15
+ public static void main (String [] args ) {
16
+ Scanner scanner = new Scanner (System .in );
17
+
18
+ System .out .print ("Enter the number of elements in the array: " );
19
+ int n = scanner .nextInt ();
20
+ int [] arr = new int [n ];
21
+
22
+ System .out .println ("Enter the elements of the array:" );
23
+ for (int i = 0 ; i < n ; i ++) {
24
+ arr [i ] = scanner .nextInt ();
25
+ }
26
+
27
+ System .out .print ("Enter the element to search for: " );
28
+ int key = scanner .nextInt ();
29
+
30
+ int index = linearSearch (arr , key );
31
+
32
+ if (index != -1 ) {
33
+ System .out .println ("Element " + key + " found at index " + index );
34
+ } else {
35
+ System .out .println ("Element " + key + " not found in the array" );
36
+ }
37
+
38
+ scanner .close ();
39
+ }
40
+ }
You can’t perform that action at this time.
0 commit comments