File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ Program to find a particular key in the array (Linear-search)
3
+ */
4
+
5
+ import java .util .Scanner ;
6
+
7
+ class LinearSearch {
8
+ public static void main (String args []){
9
+ Scanner sc = new Scanner (System .in );
10
+ System .out .println ("How many elements the array have?" );
11
+ System .out .print ("Answer : " );
12
+ try {
13
+ int [] arr = new int [sc .nextInt ()];
14
+ System .out .println ("Enter elements one by one" );
15
+ for (int i = 0 ; i < arr .length ; i ++){
16
+ System .out .print ("Enter arr[" +i +"] : " );
17
+ arr [i ] = sc .nextInt ();
18
+ }
19
+ System .out .print ("Enter the key you want to find : " );
20
+ int index = searchForKey (arr , sc .nextInt ());
21
+ if (index == -1 ){
22
+ System .out .println ("Sorry! Key is not in the array" );
23
+ }else {
24
+ System .out .println ("Key found on index -> " +index );
25
+ }
26
+ }catch (Exception e ){
27
+ System .out .println (e );
28
+ }
29
+ }
30
+
31
+ public static int searchForKey (int [] arr , int key ){
32
+ /*
33
+ This function looks for the key in the array and returns index when key found and -1 if key is not in the array.
34
+ */
35
+ for (int i =0 ; i < arr .length ; i ++){
36
+ // Searching elements one by one
37
+ if (arr [i ] == key ){
38
+ //returns index if found
39
+ return i ;
40
+ }
41
+ }
42
+ //if failed to find key return -1
43
+ return -1 ;
44
+ }
45
+ }
You can’t perform that action at this time.
0 commit comments