二分搜索技术
package sort;
import java.util.Arrays;
public class TestBinarySearch {
public static void main(String[] args) {
int[] arr ={2,5,3,8,6,4,7};
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
int i=binarySearch(arr,4);
System.out.println(i);
}
public static int binarySearch(int[] arr,int n){
int low = 0;
int high = arr.length-1;
int mid=(low+high)/2;
while(low<=high){
if(arr[mid]==n){
return mid;
}
else if(arr[mid]<n){
low=mid+1;
}else{
high=mid-1;
}
mid=(high+low)/2;
}
return mid;
}
}