a- 练习:二叉树查找数组中元素:
- import java.util.Arrays;
- class Test
- {
- public static void main(String[] args)
- {
- System.out.println(binarySearch(16));
- }
- public static int binarySearch(int num)
- {
- int[] arr = new int[]{1,5,8,11,12,14,15};
- // return Arrays.binarySearch(arr,num);
- int min,max,mid;
- min = 0;
- max = arr.length-1;
- mid = (min +max)/2;
- while(min <= max){
- if(arr[mid]==num)
- return mid;
- else
- {
- if(num<arr[mid]){
- max = mid-1;
- }
- else{
- min = mid+1;
- }
- mid = (max+min)/2;
- System.out.println("chang ...max = "+max+" min = "+min+" mid = "+mid);
- }
- }
- return -(min+1);
- }
- }
复制代码
|
|