public class BinarySearch { //递归 public static int findData(int[] a, int b, int beginIndex, int endIndex) { if(a.length == 0 || a == null) { return 0; } int length = (beginIndex + endIndex)/2; if(b == a[length]) { return length; }else if(b < a[length]) { return findData(a, b, beginIndex, length-1); }else { return findData(a, b, length+1, endIndex); } } //非递归 public static int findData2(int[] a, int des) { int left = 0 ; int right = a.length -1; while(left <= right) { int middle = (left + right)/2; if(des == a[middle]) { return middle; } if (des > a[middle]) { left = middle + 1; } if(des < a[middle]) { right = middle - 1; } } return -1; } //测试 public static void main(String[] args) { int a[] = {1,5,8,9,8}; System.out.println(a.length); int b = 9; int des = 7; //int ret = findData(a, b, 0, a.length-1); int ret = findData2(a, des); System.out.println(ret); } }