一、查找类
/** * 查找算法 * * @since 2016.09.06 * */public class BinarySearch { /** * 递归实现二分查找,返回该数字在数组中的索引 * * @param array 数组 * @param startIndex 开始索引 * @param endIndex 结束索引 * @param need 需要查找索引的数字 * @return need数字在数组中的位置(即索引) */ public static int getIndexFromArray(int[] array,int startIndex,int endIndex,int need){ if(array.length <= 0 || startIndex < 0 || endIndex < 0 || endIndex <= startIndex){ return -1; } int middleIndex = (startIndex + endIndex) / 2; if(middleIndex > array.length - 1){ return -1; } if(need == array[middleIndex]){ return middleIndex; } if(need > array[middleIndex]){ startIndex = middleIndex; }else{ endIndex = middleIndex; } return getIndexFromArray(array, startIndex, endIndex, need); } /** * 遍历查找,返回该数字在数组中的索引 * * @param array 数组 * @param need 需要查找索引的数字 * @return need数字在数组中的位置(即索引) */ public static int getIndexFromListArray(int[] array,int need){ if(array.length <= 0){ return -1; } for(int j = 0;j < array.length;j++){ if(array[j] == need){ return j; } } return -1; }}
二、测试类
public class Test { public static void main(String[] args) { int size = 9000000; int[] array = new int[size]; for(int i = 0;i < size;i++){ array[i] = i + 1; } int need = 8999999; long s = System.currentTimeMillis(); int index = BinarySearch.getIndexFromArray(array, 0, array.length, need); System.out.println("二分查找耗时:" + (System.currentTimeMillis() - s)); s = System.currentTimeMillis(); int indexRepeat = BinarySearch.getIndexFromListArray(array, need); System.out.println("遍历查找耗时:" + (System.currentTimeMillis() - s)); System.out.println(index + " || " + indexRepeat); }} 执行结果: 二分查找耗时:0 遍历查找耗时:5 8999998 || 8999998