Skip to content

Instantly share code, notes, and snippets.

@theodesp
Last active September 24, 2019 19:25
Show Gist options
  • Save theodesp/e1a8c84dc56004482b95cde634238760 to your computer and use it in GitHub Desktop.
Save theodesp/e1a8c84dc56004482b95cde634238760 to your computer and use it in GitHub Desktop.
binary search #javascript #search
/**
* Binary search element
* from a flat array of integers.
*
* @param {array} arr The array. Needs to be sorted.
* @param {int} n The element to search.
* @returns {int} Index of the element found in array
*/
function binSearch(arr, n) {
let i = 0;
let j = arr.length;
while (i<=j) {
const m = i + j >> 1;
if (arr[m] == n) {
return m;
} else if (arr[m] > n) {
j = m;
} else {
i = m;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment