import java.util.Arrays;
public class BinarySearch {
public static void main(String[] args) {
int num[] = {1,2,42,56,21,356};
System.out.println(binarySearch(num, 42));
}
/**
* 二分查找方法
* @param arr 需要查询的数组
* @param data 需要被查询的数据
*/
public static int binarySearch(int arr[],int data){
//1.对arr数组进行排序
Arrays.sort(arr);
//2.对数组进行二分查找
//数组的索引起始位置
int left = 0;
//数组的索引结束位置
int right = arr.length - 1;
//进行判断是否符合结束位置大于等于起始位置
while (left <= right){
//数组中间的索引位置
int index = (right + left ) / 2;
if (data < arr[index]){
right = index - 1;//将右边结束索引设置为 (index - 1)
}else if (data > arr[index]){
left = index + 1;//将左边结束索引设置为 (index + 1)
}else {
return index;//当相等时则输出被查询到的索引值
}
}
return -1;//都不满足的情况下输出 -1
}
}