数组二分法实现:
package array; /**数组二分法查找 * * @author jiao * @since 20201220 */ public class ArrayDome3 { public static void main(String[] args) { //二分法查找前提:数据必须是有序的 int[] arrary = {15,20,30,35,37,40,64,86}; int indexByElement = getIndexByElement(arrary,0); System.out.println(indexByElement); } private static int getIndexByElement(int[] arrary,int searchValue) { int minIndex = 0; int maxIndex = arrary.length-1; int centerIndex = (minIndex + maxIndex)/2; while (minIndex<=maxIndex){ //当查询的值等于中间坐标的,直接返回坐标 if(searchValue == arrary[centerIndex]){ return centerIndex; }else if(searchValue < arrary[centerIndex]){ //当值小于中间坐标值,maxIndex变为centerIndex-1 maxIndex = centerIndex -1; }else{ //当值大于中间坐标值,minIndex变为centerIndex+1 minIndex = centerIndex +1; } centerIndex = (minIndex + maxIndex)/2; } return -1; } }