算法描述:
当数据量很大适宜采用该方法。采用二分法查找时,数据必须是排好序的。
主要思想是:设查找的数组区间为array[low, high],中间索引 middle = (low + high)/2 ,设需要查找的数值为 value.
step1: 比较 value == array[middle],若相等,则返回索引:middle;若不相等,则进行下一步
step2:若 value < array[middle] ,则 high = middle - 1;
step3:若 value > array[middle],则 low = middle + 1;
step4: middle = (low + high)/2;
step5:当 low <= high,重复 step1~step4,直到找到,否则退出
Java 代码:
public class Test { public static int binary(int array[], int value) { int low = 0; int high = array.length - 1; int middle = 0; while(low <= high) { middle = (low + high) / 2; if(value == array[middle]){ return middle; } if(value > array[middle]) { low = middle + 1; } if(value < array[middle]) { high = middle - 1; } } return -1; } public static void main(String[] args) { int arr[] = {1, 4, 5, 12, 15, 26, 37, 48, 59}; int value = binary(arr, 12); System.out.println(value); } } // 运行结果:3