Created
December 19, 2016 14:57
-
-
Save Rosuav/b668e653b33b29919bb1db66ac94630a to your computer and use it in GitHub Desktop.
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
//Given a sorted array of numbers, find how many elements are less than a given number | |
//Do not include any NaN in the array. | |
function how_many_less(arr, n) { | |
if (!arr.length || arr[0] >= n) return 0; | |
let low = 0, high = arr.length; | |
while (high > low) { | |
let mid = Math.floor((high + low) / 2); | |
if (arr[mid] >= n) high = mid; | |
else if (arr[mid + 1] < n) low = mid; | |
else return mid + 1; | |
} | |
} | |
var arr = []; | |
while (Math.random() < 0.9) arr.push(Math.floor(Math.random() * 90 + 10)); | |
arr.sort(); | |
console.log(arr); | |
console.log(how_many_less(arr, 25)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment