用递归写个二分查找;
package CL6;
import java.util.Scanner;
public class BinarySearch {
public static int BinarySearched(int[] arr,int beginIndex,int endIndex,int value){
int mid = ((endIndex-beginIndex)>>>1)+beginIndex;
if(beginIndex>endIndex){
return -1;
}
if(arr[mid]==value){
return mid;
}else if(arr[mid]>value){
return BinarySearched(arr,beginIndex,mid-1,value);
}else {
return BinarySearched(arr, mid + 1, endIndex, value);
}
}
public static void main(String[] args) {
int[] arr = {1,3,5,7,8,9};
System.out.println("请输入一个数字");
Scanner scanner = new Scanner(System.in);
int value= scanner.nextInt();
int a =BinarySearched(arr,0,arr.length-1,value);
System.out.println(a);
}
}