Binary search doesn't see 3 and 5 from array?
-
Why does the code not see the values 3 and 5 from the array. Everything else is fine.
const arr2 = [1, 2, 2, 3, 6, 5, 6, 2, 3, 7, 8, 9, 5, 4, 6, 4, 3, 2, 2, 6, 5, 5]; arr2.sort((a, b) => a - b); console.log(countFreq(arr2, 3)) function searchElement2(arr2, el) { let left = -1; let right = arr2.length; while (right - left > 1) { const mid = Math.floor((left + right) / 2); if (arr2[mid] === el) { return mid; } if (arr2[mid] > el) { right = arr2[mid]; } else { left = mid; } } return -1; } function countFreq(arr2, el) { const posEl = searchElement2(arr2, el); if (posEl === -1) { return 0; } let i = posEl; while (arr2[i] === el) { i--; } let j = posEl; while (arr2[j] === el) { j++; } return j - i - 1; }
JavaScript Anonymous, Aug 11, 2019
0 Answers
Your Answer
To place the code, please use CodePen or similar tool. Thanks you!