Java基礎-----二分查詢
阿新 • • 發佈:2018-12-08
如果陣列是無序的不能使用二分查詢。
package StringBufferPackage; public class Demo8_getIndex { public static void main(String[] args) { int[] arr = {11,22,33,44,55,66,77}; System.out.println(getIndex(arr,55)); } private static int getIndex(int[] arr, int value) { int min = 0; int max = arr.length - 1; int mid = (min + max) / 2; while(arr[mid] != value) { if(arr[mid] > value) { max = mid - 1; } else if (arr[mid] < value) { min = mid + 1; } mid = (min + max) / 2; if (min > max) { return 0; } } return mid; } }