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));
    }
}
posted @ 2018-10-26 09:03  修电脑的龙生  阅读(287)  评论(0编辑  收藏  举报