Skip to content

Commit cea1eac

Browse files
InterviewQuestions/src/package1/BinarySearch.java
1 parent e568808 commit cea1eac

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package package1;
2+
//Given a sorted array and a target, return the index of the target in this array, return -1 if not found.
3+
public class BinarySearch {
4+
5+
6+
//if not found in array, return -1;
7+
public static int binarySearch(int[] nums, int target){
8+
if(nums == null || nums.length == 0) return -1;
9+
10+
int left = 0, right = nums.length-1;
11+
if(nums[right] < target || nums[left] > target) return -1;
12+
13+
while(left+1 < right){
14+
int mid = left + (right-left)/2;
15+
if(nums[mid] == target) return mid;
16+
else if(nums[mid] > target){
17+
right = mid;
18+
} else {
19+
left = mid;
20+
}
21+
}
22+
if(nums[left] == target) return left;
23+
else if(nums[right] == target) return right;
24+
return -1;
25+
}
26+
27+
public static void main(String...strings){
28+
29+
30+
31+
//test case 1:
32+
int[] nums = new int[]{1,2,3,4,5,6,7,8,9};//lenght = 9, 9/2 = 4
33+
// int target = 7;
34+
35+
// test case 2:
36+
// int target = 10;
37+
38+
//test case 3:
39+
// int target = -2;
40+
41+
// int target = 1;
42+
int target = 9;
43+
44+
System.out.println(binarySearch(nums, target));
45+
46+
}
47+
}

0 commit comments

Comments
 (0)