最近看MySQL索引原理,得知在InnnoDB引擎下其数据结构为B+树,而B+树每个节点上有多个key,当查找某个key时使用二分查找。所以,付下下二分查找吧~
前提:查找的数组本身应是有序的。
过程:
public class BinarySearch {
public static void main(String[] args) {
int[] values = {1, 3, 4, 5, 6, 9, 10, 34, 99};
System.out.println(binarySearch(values, 1));
System.out.println(binarySearch(values, 2));
System.out.println(binarySearch(values, 3));
System.out.println(binarySearch(values, 5));
System.out.println(binarySearch(values, 34));
System.out.println(binarySearch(values, 99));
}
public static int binarySearch(int[] values, int target) {
if (values == null || values.length == 0) {
return -1;
}
int startIndex = 0;
int endIndex = values.length - 1;
int middleIndex = 0;
while (startIndex <= endIndex) {
middleIndex = (startIndex + endIndex) / 2;
if (values[middleIndex] == target) {
return middleIndex;
} else if (values[middleIndex] < target) {
startIndex = middleIndex + 1;
} else if (values[middleIndex] > target) {
endIndex = middleIndex - 1;
}
}
return -1;
}
}