代码:
package com.wangyq.datastructrue.search;
import java.util.Arrays;
public class Binarysearch {
public static void main(String[] args) {
int[] ints = {1, 6, 18, 19, 37, 50, 61, 69, 76, 81, 83, 99, 108, 113, 114, 121, 124, 156, 180, 197};
System.out.println(Arrays.toString(ints));
int index = binarysearch(ints, 0, ints.length - 1, 114);
System.out.println("第" + (index + 1) + "个");
}
private static Integer binarysearch(int[] ints, int l, int r, int searchInt) {
if (l > r) {
return -1;
}
//取中间角标
int midIndex = (r + l) / 2;
//取中间值
int mid = ints[midIndex];
//进行比较
if (searchInt > mid) {
return binarysearch(ints, midIndex + 1, r, searchInt);
} else if (searchInt < mid) {
return binarysearch(ints, l, midIndex - 1, searchInt);
} else {
return midIndex;
}
}
}
运行结果:
[1, 6, 18, 19, 37, 50, 61, 69, 76, 81, 83, 99, 108, 113, 114, 121, 124, 156, 180, 197]
第15个