带插入点的二进制搜索 - 为什么插入点错误?

时间:2017-08-29 20:48:11

标签: javascript

大家好,感谢你的时间! 我有以下JS代码实现一个简单的二进制搜索算法:

function binarySearch( arrayWhereSearching , searchElement , comparePropertyOfArrayWhereSearching , comparePropertyOfSearchElement )
{
    var minIndex = 0 ;
    var maxIndex = arrayWhereSearching.length - 1 ;
    var currentIndex ;
    var currentElement ;

    while( minIndex <= maxIndex )
    {
        currentIndex = ( minIndex + maxIndex ) / 2 | 0 ;
        currentElement = arrayWhereSearching[currentIndex] ;

        if( currentElement[comparePropertyOfArrayWhereSearching] < searchElement[comparePropertyOfSearchElement] )
        {
            minIndex = currentIndex + 1 ;
        }
        else if( currentElement[comparePropertyOfArrayWhereSearching] > searchElement[comparePropertyOfSearchElement] )
        {
            maxIndex = currentIndex - 1 ;
        }
        else
        {
            return currentIndex ;
        }
    }

    return ~currentIndex ;
}

例如,如果我测试算法以查看当值没有进入数组时我是否在2的补码中得到插入点,那么我得到错误的值。 例如:

var ar = [ {value: 1} , {value: 2} , {value: 5} , {value: 9} , {value: 11} , {value: 13}] ;

binaryIndexOfSafehubDevice( ar , {value: 14} , "value" , "value" ) ; // return -6, which 5 in 2's complement. But I was expecting the index 6.

我错过了什么?

1 个答案:

答案 0 :(得分:0)

将最终返回语句更改为~minIndex,它应该可以解决您的问题。

currentIndex没有关于元素是否会在该索引之后或之前出现的信息。但是,如果搜索元素较大,minIndex将增加,如果元素较小,则val new_rdd = rdd.map{elem => val json: JValue = parse(elem) //Foreach element in rdd, there are some values that should be looked up from the broadcasted lookup data //"value" extracted from json val lkp_bd = broadcastLkp1.value lkp_bd.cache() val param1 = lkp_bd.filter(broadcastLkp1.value("key")==="value").select("param1").distinct() val param1ReplaceNull = if(param1.count() == 0){ "constant" } else{ param1.head().getString(0) } //create a new JSON with a different structure val new_JSON = """""" compact(render(new_JSON)) } 保持不变。