目录
二分查找
public class MyTest3 {
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
int index = getIndex(arr, 30);
System.out.println(index);
}
private static int getIndex(int[] arr, int i) {
int minIndex = 0;
int maxIndex = arr.length - 1;
int centerIndex = (minIndex + maxIndex) / 2;
while (minIndex <= maxIndex) {
if (i == arr[centerIndex]) {
return centerIndex;
} else if (i < arr[centerIndex]) {
maxIndex = centerIndex - 1;
} else if (i > arr[centerIndex]) {
minIndex = centerIndex + 1;
}
centerIndex = (minIndex + maxIndex) / 2;
}
return -1;
}
}