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 = ['中国', '德国', '美国', '日本', '法国', '意大利', '英国'];
console.log(binarySearch(items, '德国'));
console.log(binarySearch(items, '法国'));
这个二分查找英文没问题,但查找中文无法找不准确,看了下这个查找的确是有点问题,谁有比较好的二分查找demo?
陪伴而非守候
二分查找!
这个二分查找法有一点不懂
中文查询问题
问题的查找
相关分类