-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinearSearch.java
More file actions
36 lines (33 loc) · 1.01 KB
/
LinearSearch.java
File metadata and controls
36 lines (33 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// WAP for linear Search in array.
public class LinearSearch {
public static final int lSearch(String arr[], String key) {
for (int i = 0; i < arr.length; i++) {
if (key.equals(arr[i])) {
return i;
}
}
return -1;
}
public static int lSearch(int arr[], int key) {
for (int i = 0; i < arr.length; i++) {
if (key == arr[i]) {
return i;
}
}
return -1;
}
public static void main(String[] args) {
int arr[] = { 1, 3, 4, 5, 11, 2 };
String fruit[] = { "apple", "banana", "grapes", "orange", "strawberry" };
int key = 5;
System.out.println(lSearch(arr, 13));
System.out.println(lSearch(arr, 3));
int index = lSearch(arr, key);
index = lSearch(fruit, "strawberry");
if (index == -1) {
System.out.println("Not found");
} else {
System.out.println("Element is at index " + index);
}
}
}