下面的調整檢索范圍 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
字符串和數據比較
哈士奇WWW
2018-10-19 14:11:28