数据结构-查找
一、二分查找
必须为有序数组
1.1递归实现
static int recursive(int[] arr,int low,int high,int target){ if(target < arr[low] || target >arr[high] || low> high){ return -1; } int middle = (low + high)/2; if(arr[middle] <target){ return recursive(arr, middle+1, high, target); }else if(arr[middle]>target){ return recursive(arr,0,middle-1, target); } else{ return middle; } }
1.2 循环实现
public static void main(String[] args) { Arrays.sort(array); int num = 1; int end = array.length-1,begin=0; while(array[(begin + end)/2] != num){ if(num < array[(begin + end)/2]){ end = (begin + end)/2; } else{ begin=(begin + end)/2; } } System.out.println((begin + end)/2); }