Answer the question
In order to leave comments, you need to log in
Is binary search correct?
const binarySearch = (list, n) => {
let start = 0,
end = list.length - 1,
mid;
while(start <= end) {
mid = Math.floor((start + end) / 2);
if (n < list[mid]) {
end = mid - 1;
} else if (n > list[mid]) {
start = mid + 1;
} else {
return `Искомое ${n} найдено на ${mid} индексе(${list[mid]})`;
}
}
return `Искомое ${n} не найдено!`;
}
Answer the question
In order to leave comments, you need to log in
mid = Math.floor((start + end) / 2);
You can not calculate in advance and write only inside the while loop.
n !== list[mid]
If the desired value is in the middle, then your binary search will break. This condition must be removed, because there is
else {
return `Искомое ${n} найдено на ${mid} индексе(${list[mid]})`;
}
mid !== start && mid !== end
floor
bugs, there may be bugs, and the search may end earlier. Better to replace withstart <= end
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question