Last active
March 17, 2018 18:02
-
-
Save mdmen/eb5578cd32095cea64e1825499816577 to your computer and use it in GitHub Desktop.
Binary search in ES6
This file contains 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
/** | |
* 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