根据数值获取下标位置
public class Test {/*** @param args* @throws IOException */public static void main(String[] args) {int[] arr = {12,14,15,53,435,888,904};int number = add(arr, 53);System.out.PRintln(number);}public static int add(int[] arr, int target) {int max = arr.length - 1;int min = 0;int mid = (max + min)/2;while (true) {if (target > arr[mid]) {min = mid+1;}else if (target < arr[mid]) {max = mid - 1;}else {return mid;}if (max < min) {return -1;}mid = (min+max)/2;}}}
也可以调用系统中的方法
二分查找法必须是有序
int[] arr = {12,14,15,53,435,888,904};Arrays.sort(arr);int index =Arrays.binarySearch(arr, 53);System.out.println(index);
如果能找到对应的元素,会返回下标,如果找不到就返回负数表示
新闻热点
疑难解答