-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearch.java
More file actions
33 lines (28 loc) · 882 Bytes
/
BinarySearch.java
File metadata and controls
33 lines (28 loc) · 882 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
29
30
31
32
33
class BinarySearch {
public int search(int[] nums, int target) {
int start = 0;
int end = nums.length-1;
while(start <= end){
int mid = (start + end)/2;
if(nums[mid] == target){
return mid;
}
else if(target >= nums[mid]){
start = mid + 1;
}
else{
end = mid - 1;
}
}
return -1;
}
public static void main(String[] args) {
BinarySearch solution = new BinarySearch();
int[] nums1 = {-1, 0, 3, 5, 9, 12};
System.out.println(solution.search(nums1, 9));
int[] nums2 = {-1, 0, 3, 5, 9, 12};
System.out.println(solution.search(nums2, 2));
int[] nums3 = {5};
System.out.println(solution.search(nums3, 5));
}
}