经典查找算法(java)
二分查找
import java.util.Arrays;
/**
* @author kiki
* @version 1.0
* @create 2020/7/7 21:42
*/
public class ErFenSearch {
public static void main(String[] args) {
int[] arr={12,45,78,98,40,4,15,8,17,89,56,10};
System.out.println("===========排序前================");
System.out.println(Arrays.toString(arr));
System.out.println("===========排序后================");
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
//查找后得到的下标
System.out.println("=========查找后得到的下标=========");
System.out.println(search(arr, 40));
}
public static int search(int[] arr,int value){
int low = 0;
int high = arr.length-1;
while (low<=high){
int mid = (low+high)/2;
if (arr[mid]==value){return mid;}
if (arr[mid]<value){low = mid+1;}
if (arr[mid]>value){high = mid-1;}
}
return -1;
}
}