-
Notifications
You must be signed in to change notification settings - Fork 0
/
binarySearch.java
57 lines (55 loc) · 1.56 KB
/
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
public class binarySearch {
public static void main(String[] args) {
int target = 7;
int[] array = new int[] { 1, 2, 3, 4, 6 };
System.out.println("target=" + target);
int i = binarySearch(array, target, 0, array.length - 1);
System.out.println("1recursion=" + i);
int j = binarySearchRecursion(array, target, 0, array.length - 1);
System.out.println("circulation=" + j);
}
/**
* circulation
*
* @param array
* @param target
* @param start
* @param end
* @return
*/
public static int binarySearch(int[] array, int target, int start, int end) {
if (start>end) {
return -1;
}
int middle = start + ((end - start)>>2);
if (target == array[middle]) {
return middle;
} else if (target > array[middle]) {
return binarySearch(array, target, middle + 1, end);
} else {
return binarySearch(array, target, start, middle - 1);
}
}
/**
* recursion
*
* @param array
* @param target
* @param start
* @param end
* @return
*/
public static int binarySearchRecursion(int[] array, int target, int start, int end) {
while (start <= end) {
int mid = start + ((end - start) >> 2);
if (array[mid] == target) {
return mid;
} else if (target<array[mid]) {
end = mid - 1;
} else {
start = mid + 1;
}
}
return -1;
}
}