二分查找(递归和非递归方式)
public class erfenchazhao { public static void main(String[] args) { int [] num ={1, 2, 2, 3, 4, 5, 7, 9, 10, 11}; int search = search(num, 14); System.out.println(search); //-------------------------- int max = num.length - 1; int min =0; int search2 = search2(num, max, min, 6); System.out.println(search2); } //递归 private static int search2(int[] num, int max, int min ,int i) { int index =(max+min)/2; if(max >= min){ if(num[index]== i){ return index +1; }else if (num[index]>i){ search2(num,index-1,min,i); }else { search2(num,max,index+1,i); } } return -1; } //非递归 private static int search(int[] num, int i) { int length = num.length-1; int start = 0; while (start <= length){ int index = (length+start)/2; if(num[index] == i){ return index+1; }else if (num[index] >i){ length = index-1; }else{ start = index+1; } } return -1; } }