现在的位置: 首页 > 综合 > 正文

javascript二分法

2013年06月29日 ⁄ 综合 ⁄ 共 622字 ⁄ 字号 评论关闭
//Copyright 2009 Nicholas C. Zakas. All rights reserved.
//MIT-Licensed, see source file
function binarySearch(items, value){
 
    var startIndex  = 0,
        stopIndex   = items.length - 1,
        middle      = Math.floor((stopIndex + startIndex)/2);
 
    while(items[middle] != value && startIndex < stopIndex){
 
        //adjust search area(调整查找范围)
        if (value < items[middle]){
            stopIndex = middle - 1;
        } else if (value > items[middle]){
            startIndex = middle + 1;
        }
 
        //recalculate middle(重新计算中项索引)
        middle = Math.floor((stopIndex + startIndex)/2);
    }
 
    //make sure it's the right value(确保返回正确的值)
    return (items[middle] != value) ? -1 : middle;
}

抱歉!评论已关闭.