Skip to content

Instantly share code, notes, and snippets.

@kraftdorian
Created December 17, 2022 19:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kraftdorian/b4dbacb34720a71e4166798f40cdcc49 to your computer and use it in GitHub Desktop.
Save kraftdorian/b4dbacb34720a71e4166798f40cdcc49 to your computer and use it in GitHub Desktop.
/**
* @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