Skip to content

Instantly share code, notes, and snippets.

@greathmaster
Created May 26, 2020 18:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save greathmaster/820066e8504fad79de76fbba10ab0846 to your computer and use it in GitHub Desktop.
Save greathmaster/820066e8504fad79de76fbba10ab0846 to your computer and use it in GitHub Desktop.
Binary Search Variations
/*
Given an array of 1's and 0's in the following format:
[1, 1, 1, 0, 0]
Use binary search to determine how many 1's are in the array.
You can assume the 1's will always appear together and at the
beginning of the array.
*/
function bs(array) {
let left = 0;
let right = array.length;
let mid = Math.floor((left + right) / 2);
while (left < right) {
mid = Math.floor((left + right) / 2);
if (array[mid] == 1) {
left = mid + 1;
} else {
right = mid;
}
}
return left;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment