forked from haitong/Lintcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearch.java
More file actions
executable file
·51 lines (44 loc) · 1.32 KB
/
BinarySearch.java
File metadata and controls
executable file
·51 lines (44 loc) · 1.32 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
41
42
43
44
45
46
47
48
49
50
51
public class BinarySearch {
public static int binarySearch(int[] nums, int target) {
if (nums == null || nums.length == 0) {
return -1;
}
int start = 0;
int end = nums.length - 1;
while (start + 1 < end) {
int mid = start + (end - start) / 2;
if (nums[mid] == target) {
end = mid;
} else if (nums[mid] < target) {
start = mid;
} else {
end = mid;
}
}
if (nums[start] == target) {
return start;
}
if (nums[end] == target) {
return end;
}
return -1;
}
public static int binarySearchRecursive(int[] a, int x, int low, int high) {
if (low > high) return -1; // Error
int mid = (low + high) / 2;
if (a[mid] < x) {
return binarySearchRecursive(a, x, mid + 1, high);
} else if (a[mid] > x) {
return binarySearchRecursive(a, x, low, mid - 1);
} else {
return mid;
}
}
public static void main(String[] args) {
int[] array = {3, 6, 9, 12, 15, 18};
int loc = binarySearch(array, 9);
int loc2 = binarySearchRecursive(array, 9, 0, array.length - 1);
System.out.println(loc);
System.out.println(loc2);
}
}