-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary search.java
More file actions
28 lines (28 loc) · 916 Bytes
/
binary search.java
File metadata and controls
28 lines (28 loc) · 916 Bytes
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
public class Main {
public static int search(int[] nums, int target) {
return binarySearch(nums, 0, nums.length - 1, target);
}
public static int binarySearch(int[] nums, int low, int high, int target) {
if (low > high) {
return -1;
}
int mid = (low + high) / 2;
if (nums[mid] == target) {
return mid;
} else if (target > nums[mid]) {
return binarySearch(nums, mid + 1, high, target);
} else {
return binarySearch(nums, low, mid - 1, target);
}
}
public static void main(String[] args) {
int[] a = {3, 4, 6, 7, 9, 12, 16, 17};
int target = 6;
int ind = search(a, target);
if (ind == -1) {
System.out.println("The target is not present.");
} else {
System.out.println("The target is at index: " + ind);
}
}
}