-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinearSearch.java
More file actions
51 lines (44 loc) · 1.55 KB
/
LinearSearch.java
File metadata and controls
51 lines (44 loc) · 1.55 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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
comparison between the iterative and recursive versions of a linear search in Java.
Iterative Linear Search
public class LinearSearch {
public static int linearSearchIterative(int[] arr, int x) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == x) {
return i; // Return the index where the element is found
}
}
return -1; // Element not found in the array
}
public static void main(String[] args) {
int[] arr = {2, 3, 4, 10, 40};
int x = 10;
int result = linearSearchIterative(arr, x);
if (result == -1) {
System.out.println("Element not present in array");
} else {
System.out.println("Element found at index " + result);
}
}
}
Recursive Linear Search
public class LinearSearch {
public static int linearSearchRecursive(int[] arr, int x, int index) {
if (index >= arr.length) {
return -1; // Base case: element not found
}
if (arr[index] == x) {
return index; // Element found, return its index
}
return linearSearchRecursive(arr, x, index + 1); // Recursive call to check the next element
}
public static void main(String[] args) {
int[] arr = {2, 3, 4, 10, 40};
int x = 10;
int result = linearSearchRecursive(arr, x, 0);
if (result == -1) {
System.out.println("Element not present in array");
} else {
System.out.println("Element found at index " + result);
}
}
}