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?
這個二分查找中文有問題
www說
2018-12-19 16:18:41