Skip to content

Instantly share code, notes, and snippets.

@Rosuav
Created December 19, 2016 14:57
Show Gist options
  • Save Rosuav/b668e653b33b29919bb1db66ac94630a to your computer and use it in GitHub Desktop.
Save Rosuav/b668e653b33b29919bb1db66ac94630a to your computer and use it in GitHub Desktop.
//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