查找数组下标,索引,二分
二分查找数组,数组必须是有序的
按照从小到大排序
import java.util.Arrays;
public class ErFentest {
public static void main(String[] args) {
//二分查找数组,,数组必须按照从小到大排序
int index = f(4);//找14的索引
System.out.println(index);//打印14的索引
}
public static int f(int args) {
int[] a = {1,4,8,12,20,24};
int s = 0;//开始索引
int e = a.length - 1;//结束索引
while (s <= e) {
int m = (s + e) / 2;//取中间数字索引
if (a[m] == args) {
return m;//返回该数索引
} else if (a[m] > args) {
e = m - 1;
} else {
s = m + 1;
}
}
return -1;//不在返回-1
}
}