代码:
/** | |
* 使用 while 查找值所在位置 | |
* @param arr 目标数组,必须是排序后的 | |
* @param value 查找目标值 | |
* @return 位置 | |
*/ | |
private static Integer binarySearch1( Integer[] arr, Integer value ){ | |
int low = 0; | |
int high = arr.length-1; | |
while ( low<high ){ | |
int middle = (low+high)/2; | |
if ( value == arr[middle] ){ | |
return middle; | |
} | |
if ( value < arr[middle] ){ | |
high = middle-1; | |
} | |
if ( value > arr[middle] ){ | |
low = middle+1; | |
} | |
} | |
return -1; | |
} | |
/** | |
* 递归查询 | |
* @param arr 目标数组,必须是排序后的 | |
* @param value 查找目标值 | |
* @param startIndex 起始位置 | |
* @param endIndex 结束位置 | |
* @return 位置 | |
*/ | |
private static Integer binarySearch2( Integer[] arr,Integer value,Integer startIndex,Integer endIndex ){ | |
int middleIndex = (startIndex+endIndex)/2; | |
if ( value<arr[startIndex] || value>arr[endIndex] ){ | |
return -1; | |
} | |
if ( value<arr[middleIndex] ){ | |
return binarySearch2( arr,value,startIndex,middleIndex-1 ); | |
} | |
if ( value>arr[middleIndex] ){ | |
return binarySearch2( arr,value,middleIndex+1,endIndex ); | |
}else { | |
return middleIndex; | |
} | |
} | |
public static void main(String[] args) { | |
Integer[] arr1 = new Integer[]{2,14,65,23,41,12,54,23,56,20}; | |
Arrays.sort(arr1); | |
System.out.println( Arrays.asList(arr1).toString() ); | |
Integer result1 = binarySearch1(arr1,54); | |
System.out.println(result1); | |
Integer[] arr2 = new Integer[]{2,14,65,23,41,12,54,23,56,20}; | |
Arrays.sort(arr2); | |
System.out.println( Arrays.asList(arr2).toString() ); | |
Integer result2 = binarySearch2(arr2,56,0,arr2.length-1); | |
System.out.println(result2); | |
} |
运行结果:
[2, 12, 14, 20, 23, 23, 41, 54, 56, 65]
7
[2, 12, 14, 20, 23, 23, 41, 54, 56, 65]
8
(转自网上)