Answer the question
In order to leave comments, you need to log in
Is the algorithm not working correctly?
finds numbers up to 5 field throws errors about an infinite loop
function bin(arr, val) {
let mid = Math.floor(arr.length / 2)
while (mid >= 0 && mid <= arr.length) {
if (arr[mid] === val) {
return arr[mid]
}
if (arr[mid] > val) {
mid = Math.floor(mid / 2)
}
if (arr[mid] < val) {
mid = Math.floor((arr.length - mid) / 2)
}
}
}
console.log(bin([1, 2, 3, 4, 5, 6, 7, 8, 9,], 7));
Answer the question
In order to leave comments, you need to log in
Binsearch maintains the current segment, which may contain the searched element. Looks at the middle and discards one of the halves of the segment.
You are somehow trying to implement this only with the mid variable. If you need to go to the left, then you divide mid in half, as if the current segment from the beginning of the array (But this is not always the case: after the first step to the right, the beginning of the array will already be thrown out of consideration), Then, when moving to the right, you have some then nonsense is written.
Math.floor((arr.length - mid) / 2)
- what is it supposed to do? If mid=9, length = 10, you will generally go to the beginning of the array, although you should go to the right. If you wanted to take the middle between mid and length, then there should be a "+" inside.
But it still can't be done that way. Enter 2 variables l and r, as in all binsearch implementations, consider mid as the middle of the segment, and when throwing out one of the halves, simply rewrite l or r to mid+1 or mid-1 (because you have already considered the mid element itself and it is exactly not needed).
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question