forked from mattmiller1426/Hacktobber2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinearSearch.java
64 lines (56 loc) · 1.81 KB
/
LinearSearch.java
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
public class Main {
public static void main(String[] args) {
int[] nums = {93, 45, 31, 2, 8, 19, -3, 69, -11, 28};
int target = 28;
boolean ans = linearSearch3(nums, target);
System.out.println(ans);
}
// search the target and return true or false
static boolean linearSearch3(int[] arr, int target) {
if (arr.length == 0) {
return false;
}
// run a for loop
for (int element : arr) {
if (element == target) {
return true;
}
}
// this line will execute if none of the return statements above have executed
// hence the target not found
return false;
}
// search the target and return the element
static int linearSearch2(int[] arr, int target) {
if (arr.length == 0) {
return -1;
}
// run a for loop
for (int element : arr) {
if (element == target) {
return element;
}
}
// this line will execute if none of the return statements above have executed
// hence the target not found
return Integer.MAX_VALUE;
}
// search in the array: return the index if item found
// otherwise if item not found return -1
static int linearSearch(int[] arr, int target) {
if (arr.length == 0) {
return -1;
}
// run a for loop
for (int index = 0; index < arr.length; index++) {
// check for element at every index if it is = target
int element = arr[index];
if (element == target) {
return index;
}
}
// this line will execute if none of the return statements above have executed
// hence the target not found
return -1;
}
}