Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

下面的调整检索范围 value是一个字符串items[middle]是一个数字
这两个是怎么做的比较????

function binarySearch(items, value){
            var startIndex  = 0,
                stopIndex   = items.length - 1,
                middle      = Math.floor((stopIndex + startIndex)/2);

            while(items[middle] != value && startIndex < stopIndex){
                //调整检索范围
                if (value < items[middle]){
                    stopIndex = middle - 1;
                } else if (value > items[middle]){
                    startIndex = middle + 1;
                }
                //重新计算中间值
                middle = Math.floor((stopIndex + startIndex)/2);
            }
            //判断是否找到要搜索的值
            return (items[middle] != value) ? -1 : middle;
        }   
        var items = ["a","b","c","d","e","f","g","h","i","j"];
        console.log(binarySearch(items, "i"));    //8
        console.log(binarySearch(items, "b"));   //1    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
209 views
Welcome To Ask or Share your Answers For Others

1 Answer


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...