-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearch.java
More file actions
40 lines (34 loc) · 1.03 KB
/
BinarySearch.java
File metadata and controls
40 lines (34 loc) · 1.03 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
package Searching;
public class BinarySearch {
static boolean binarySearch(int[] a, int target) {
int st = 0, end = a.length - 1;
while (st <= end) {
int mid = st + (end - st) / 2;
if (target == a[mid]) {
return true;
} else if (target < a[mid]) {
end = mid - 1;
} else {
st = mid + 1;
}
}
return false;
}
static boolean recursiveBinarySearch(int[] a, int st, int end, int target) {
// Base Case
if (st > end)
return false;
// Mid and Self-Work
int mid = st + (end - st) / 2;
if (target == a[mid])
return true;
else if (target > a[mid])
return recursiveBinarySearch(a, mid + 1, end, target);
else
return recursiveBinarySearch(a, st, mid - 1, target);
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
System.out.println(binarySearch(arr, 3));
}
}