binary search(二分法):
代码:
import java.util.Arrays;/*** 二分法查找元素*/
public class BinarySearch {public static void main(String[] args) {int[] arr = {30,20,50,10,80,9,7,12,100,40,8};int searchWord = 20;//要查找的值System.out.println(searchWord+"索引位置:"+binarySearch(arr,searchWord));}/**** @param array 目标数组* @param value 所要查找的值* @return 如果找到,则返回这个值在数组中的索引,如果未找到,则返回-1;*/public static int binarySearch(int[] array,int value){//二分法查找的数组,戏必须先排序Arrays.sort(array);System.out.println(Arrays.toString(array));int low = 0;int high = array.length-1;while(low<=high){int 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;//未找到返回-1}
}
执行结果: