Last active
September 24, 2019 19:25
-
-
Save theodesp/e1a8c84dc56004482b95cde634238760 to your computer and use it in GitHub Desktop.
binary search #javascript #search
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
/** | |
* 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