Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 1324f1c

Browse files
sarthak-trivediabranhe
authored andcommittedOct 6, 2020
Java linear search
1 parent dc30e97 commit 1324f1c

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
 

‎data-structures/LinearSearch.java

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

0 commit comments

Comments
 (0)
Please sign in to comment.