Created
December 17, 2022 19:53
-
-
Save kraftdorian/b4dbacb34720a71e4166798f40cdcc49 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {Array<number>} arr Numeric array | |
* @param {number} needle Value to search for | |
* @return {number} -1 if value was not found, positive value index otherwise | |
*/ | |
function binarySearch(arr, needle) { | |
if (!Array.isArray(arr) || needle == null) { | |
return -1; | |
} | |
// pre-requisite: sort the array, ascending order | |
arr.sort(); | |
let leftPtr = 0, | |
rightPtr = arr.length - 1, | |
midPtr; | |
while (leftPtr <= rightPtr) { | |
midPtr = Math.floor((leftPtr + rightPtr) / 2); | |
if (arr[midPtr] === needle) { | |
return midPtr; | |
} else if (arr[midPtr] < needle) { | |
// value at the middle pointer is smaller than the needle, | |
// that means we need to shift to the right side, | |
// by moving the left pointer to middle pointer + 1 | |
leftPtr = midPtr + 1; | |
} else { | |
// value at the middle pointer is bigger than the target, | |
// that means we need to shift to the left side, | |
// by moving the right pointer to middle pointer - 1 | |
rightPtr = midPtr - 1; | |
} | |
} | |
return -1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment