-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinarySearch.java
30 lines (29 loc) · 957 Bytes
/
BinarySearch.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
class Solution {
public int search(int[] nums, int target) {
int size = nums.length;
int left = 0,right= size-1;
int ans = BinarySearch(left, right, target, nums);
return ans;
}
public static int BinarySearch(int left,int right,int target,int nums[]){
if( right >= left ){
int mid = left + (right-left) / 2;
if( target < nums[mid] ){
//towards left
return BinarySearch(left, mid-1, target, nums);
}
if( nums[mid] == target ){
//return mid
return mid;
}
return BinarySearch(mid+1, right, target, nums);
}
return -1;
}
public static void main(String[] args) {
int[] nums = {-1,0,3,5,9,12};
int target = 9;
Solution solution = new Solution();
System.out.println( solution.search(nums, target) );
}
}