Как реализовать бинарный поиск в JavaScript
Я следовал псевдокоду для реализации алгоритма по ссылке, но не знаю, что не так с моим кодом.
Вот мой код:
/* Returns either the index of the location in the array,
or -1 if the array did not contain the targetValue */
var doSearch = function(array, targetValue) {
var min = 0;
var max = array.length - 1;
var guess;
while(min < max) {
guess = (max + min) / 2;
if (array[guess] === targetValue) {
return guess;
}
else if (array[guess] < targetValue) {
min = guess + 1;
}
else {
max = guess - 1;
}
}
return -1;
};
var primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37,
41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97];
var result = doSearch(primes, 2);
println("Found prime at index " + result);
//Program.assertEqual(doSearch(primes, 73), 20);
4 ответа
Чтобы получить значение из массива, вам нужно указать целое число, например array[1]
, array[1.25]
вернусь undefined
в твоем случае.
Чтобы это заработало, я просто добавил Math.floor
внутри вас, чтобы убедиться, что мы получаем целое число.
РЕДАКТИРОВАТЬ: как @KarelG pointet, вы также должны добавить <=
в вашем цикле Это для ситуаций, когда min
а также max
стали такими же, и в этом случае guess === max === min
, Без <=
цикл не будет работать в этих ситуациях и функция вернет -1
,
function (array, targetValue) {
var min = 0;
var max = array.length - 1;
var guess;
while(min <= max) {
guess = Math.floor((max + min) / 2);
if (array[guess] === targetValue) {
return guess;
}
else if (array[guess] < targetValue) {
min = guess + 1;
}
else {
max = guess - 1;
}
}
return -1;
}
Вы можете использовать любой из Math.floor
, Math.ceil
, а также Math.round
,
Я надеюсь, что это была небольшая помощь, я не очень хорош в объяснении, но я приложу все усилия, чтобы уточнить.
В вашем коде, когда min равно max, цикл заканчивается. Но в этом сценарии вы не проверяете, array[min] == targetValue
Таким образом, изменение кода на это, скорее всего, решит вашу проблему
/* Returns either the index of the location in the array,
or -1 if the array did not contain the targetValue */
var doSearch = function(array, targetValue) {
var min = 0;
var max = array.length - 1;
var guess;
while(min <= max) {
guess = Math.floor((max + min) / 2);
if (array[guess] === targetValue) {
return guess;
}
else if (array[guess] < targetValue) {
min = guess + 1;
}
else {
max = guess - 1;
}
}
return -1;
};
JSFiddle Link: http://jsfiddle.net/7zfph6ks/
Надеюсь, поможет.
PS: только изменение в коде это строка: while (min <= max)
Вам нужно только раскомментировать Program.assertEqual следующим образом:
Program.assertEqual(doSearch(primes, 73), 20);
не так:
//Program.assertEqual(doSearch(primes, 73), 20);
Если кто-то все еще ищет ответ, вам нужно его сделать (max >= min)
while (max >= min) {
guess = Math.floor((max + min) / 2);
if (array[guess] === targetValue) {
return guess;
}
else if (array[guess] < targetValue) {
min = guess + 1;
}
else {
max = guess - 1;
}
}
return -1;