第一次出现在二进制搜索 [英] First occurrence in a binary search

查看:166
本文介绍了第一次出现在二进制搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我与一些code修修补补,我意识到这是我从来不知道。一个正常的二进制搜索将在数据集返回一个随机指数为出现一次以上的一个关键。如何修改低于此code返回的第一次出现的?这是不是人呢?

  //从JDK撕开
公共静态INT binarySearchValue(InvertedContainer.InvertedIndex []一,长键){
    返回bSearchVal(一,0,则为a.length,密钥);
}私有静态诠释bSearchVal(InvertedContainer.InvertedIndex []一,诠释的fromIndex,
                                 INT元素范围为长键){
    诠释低=的fromIndex;
    INT高=元素范围为 - 1;    而(低< =高){
        INT中旬=(低+高)GT;>> 1;
        长midVal = A [MID] .VAL;        如果(midVal&所述密钥)
            低=中旬+ 1;
        否则如果(midVal>键)
            高=中旬 - 1;
        其他
            返回中旬; //找到关键
    }
    返回(低); //没有找到钥匙。返回插入点
}


解决方案

已经发现的的匹配值,则基本上需要步行集合,直到你找到它的的条目不的匹配。

您可以的可能的使其更快获取通过一键立即比你正在寻找一个较低的指数,然后做两者之间的二元斩 - 但我可能会去的简单的版本,这很可能是足够有效的,除非你有一个很大数字相同的条目。

I'm tinkering with some code and I realized something I never knew. A normal binary search will return a random index in a data set for a key that occurs more than once. How can I modify this code below to return the first occurrence? Is this something people do?

//ripped from the JDK
public static int binarySearchValue(InvertedContainer.InvertedIndex[] a, long key) {
    return bSearchVal(a, 0, a.length, key);
}

private static int bSearchVal(InvertedContainer.InvertedIndex[] a, int fromIndex,
                                 int toIndex, long key) {
    int low = fromIndex;
    int high = toIndex - 1;

    while (low <= high) {
        int mid = (low + high) >>> 1;
        long midVal = a[mid].val;

        if (midVal < key)
            low = mid + 1;
        else if (midVal > key)
            high = mid - 1;
        else
            return mid; // key found
    }
    return (low); // key not found. return insertion point
}

解决方案

Having found a matching value, you basically need to walk up the collection until you find an entry which doesn't match.

You could potentially make it faster by fetching the index of a key immediately lower than the one you were looking for, then do a binary chop between the two - but I'd probably go for the simpler version, which is likely to be "efficient enough" unless you've got a really large number of equal entries.

这篇关于第一次出现在二进制搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆