zoukankan      html  css  js  c++  java
  • 用二分查找——查找比目标元素略大的索引

     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 }
    人生苦短,及时行乐
  • 相关阅读:
    matrix
    meizi
    公文流转系统
    10.21连接数据库进行添加
    9.27
    9.23课堂总结
    信息管理java
    大道至简读后感
    第二周
    7.7第一周
  • 原文地址:https://www.cnblogs.com/lang-zi/p/12411607.html
Copyright © 2011-2022 走看看