二分法查找(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
import org.junit.Test;

/**
* 二分法查找
*/
public class BinarySearch {

@Test
public void test() {
System.out.println(binarySearch(new int[]{3, 5, 7, 8, 10}, 8));
}

public int binarySearch(int[] arr, int value) {
return binarySearch(arr, 0, arr.length - 1, value);
}

public int binarySearch(int[] arr, int begin, int end, int value) {
if (begin > end) {
return -1;
}
int middleIndex = (begin + end) / 2;
int middleValue = arr[middleIndex];
if (value == middleValue) {
return middleIndex;
} else if (value < middleValue) {
return binarySearch(arr, begin, middleIndex - 1, value);
} else if (value > middleValue) {
return binarySearch(arr, middleIndex + 1, end, value);
}
return -1;
}

}