1. 程式人生 > >Java基礎-----二分查詢

Java基礎-----二分查詢

如果陣列是無序的不能使用二分查詢。

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;
	}
}