Skip to content

Instantly share code, notes, and snippets.

@mdmen
Last active March 17, 2018 18:02
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 mdmen/eb5578cd32095cea64e1825499816577 to your computer and use it in GitHub Desktop.
Save mdmen/eb5578cd32095cea64e1825499816577 to your computer and use it in GitHub Desktop.
Binary search in ES6
/**
* Binary search
* @param {array} list - Array of numbers for search
* @param {number} elem - Looking item
* @returns {number|null} - Found index or null if not found
*/
const binarySearch = (list, elem) => {
let startIndex = 0;
let lastIndex = list.length - 1;
while (startIndex <= lastIndex) {
let index = Math.floor((startIndex + lastIndex) / 2);
if (list[index] === elem) {
return index;
}
if (list[index] < elem) {
startIndex = index + 1;
} else {
lastIndex = index - 1;
}
}
return null;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment