我創建了函數getIndex
獲取索引,我從數組中搜索索引。JavaScript while while循環不起作用
當我改變了while (1)
,而不是while (max < min)
這個循環是否正常工作,但條件(while (max < min)
)它的返回-1。但我需要條件檢查,如果我的搜索不存在於data
陣列中。爲什麼它返回-1的條件?
// assume my array looks-like this.
var data = [1, 2, 3, 4, 5, 7, 8, 9, 10];
function getIndex(search, arr) {
var min, max, guess, count;
min = 0;
max = arr.length - 1;
count = 0;
// If my search is not present in array. Return -1.
while (max < min) {
count++;
guess = Math.floor((min + max)/2);
if (arr[guess] === search) {
return guess;
} else if (arr[guess] < search) {
min = guess + 1;
} else {
max = guess - 1;
}
}
return -1;
}
getIndex(8, data); // return -1
爲什麼不你只需要使用'data.indexOf(search)'? –
爲什麼你使用一種特殊和最糟糕的方式(在時間複雜度方面)來搜索數組? –