今天学习了二分查找,虽然代码简单,但还是要有必要,记录一下今天的学习的。
1 public class TestBrinarySeach { 2 public static void main(String[] args) { 3 int[] arr = {24,32,15,56,39,44,87,65,59}; 4 Arrays.sort(arr); 5 6 int value = 39;//要查找的值 7 8 System.out.println(Arrays.toString(arr)); 9 System.out.println(myBrinarySeach(arr, value)+1); 10 11 } 12 13 14 15 public static int myBrinarySeach(int[] arr,int value){ 16 int low = 0; 17 int high = arr.length-1; 18 19 while(low<=high){ 20 int mid = (low+high)/2; 21 22 if(value==arr[mid]){ 23 return mid; 24 } 25 if(value>arr[mid]){ 26 low = mid+1; 27 } 28 if(value<arr[mid]){ 29 high = mid-1; 30 } 31 } 32 return -1; 33 } 34 }