用二分查找——查找比目标元素略大的索引

 1 public class 二分查找 {
 2 //************************二分查找*******************
 3     static int f(int[]a,int begin,int end,int x) {
 4         if(end-begin==1) {
 5             if(a[begin]>x)return begin;
 6             return end;
 7         }//出口
 8         int k=(begin+end)/2;
 9         if(x>=a[k])return f(a,k,end,x);//如果x大于中间元素查找后半段
10         return f(a,begin,k,x);
11         
12         
13     }
14      
15     static int f(int[] a,int x) {
16         if(x>=a[a.length-1])return -1;//如果要查找元素比数组中的元素都大返回-1
17         
18         return f(a,0,a.length,x);    //递归调用
19     }
20     
21     
22     
23     public static void main(String[] args) {
24 int[] a= {3,5,6,9,10,13,15,19,26,36,45,66,99,100,123,254,564};
25 System.out.println(f(a,13));
26         //查找比相应元素略大的元素位置
27 
28         
29 
30     }
31 
32 }

 

posted @ 2020-03-04 19:26  浪~子  阅读(301)  评论(0编辑  收藏  举报