zoukankan      html  css  js  c++  java
  • Algs4-1.4.10二分查找找出元素所在的最小索引

    1.4.10修改二分查找算法,使之总是返回和被查找的键匹配的索引最小元素(且仍然能够保证对数级别的运行时间)。
    答: 以下代码rankMin。
    图片

    import java.util.Arrays;
    public class BinarySearch
    {
        public static int rank(int key,int[]a)
        {
            int lo=0;
            int hi=a.length-1;
            int keyIndex=-1;
            while (lo<=hi)
            {
                int mid=lo+(hi-lo)/2;
                if (key<a[mid]) hi=mid-1;
                else if(key>a[mid]) lo=mid+1;
                else  return mid;
             }
            return keyIndex;
         }
       
        public static int rankMin(int key,int[]a)
        {
            int lo=0;
            int hi=a.length-1;
            int keyIndex=-1;
            while (lo<=hi)
            {
                int mid=lo+(hi-lo)/2;
                if (key<a[mid]) hi=mid-1;
                else if(key>a[mid]) lo=mid+1;
                else
                {
                  keyIndex=mid;
                  hi=mid-1;
                }
            }
            return keyIndex;
         }
       
            public static int rankMax(int key,int[]a)
        {
            int lo=0;
            int hi=a.length-1;
            int keyIndex=-1;
            while (lo<=hi)
            {
                int mid=lo+(hi-lo)/2;
                if (key<a[mid]) hi=mid-1;
                else if(key>a[mid]) lo=mid+1;
                else
                {
                  keyIndex=mid;
                  lo=mid+1;
                }
            }
            return keyIndex;
         }

        public static void main(String[] args)
        {
            int[] whitelist=In.readInts(args[0]);
            int key=Integer.parseInt(args[1]);
            Arrays.sort(whitelist);
            StdOut.println("Key rank index is:"+ rank(key,whitelist));
            StdOut.println("Key rankMin index is:"+ rankMin(key,whitelist));
            StdOut.println("Key rankMax index is:"+ rankMax(key,whitelist));
        }
    }
  • 相关阅读:
    java.lang.NoClassDefFoundError:org/apache/commons/lang/exception/NestableRuntimeException错误的解决
    json转换成对象
    16年4月20号 个人总结
    sql between and
    sql 中的运算符级别 如and or not
    mybatis int 类型判断<if>
    iOS地址编码解析
    iosiOS 地图 自定义以及添加锚点
    ios如何获取位置权限
    如何初始化一个iOS原生地图
  • 原文地址:https://www.cnblogs.com/longjin2018/p/9854410.html
Copyright © 2011-2022 走看看