我创建了函数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)'? –
为什么你使用一种特殊和最糟糕的方式(在时间复杂度方面)来搜索数组? –