Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@clarketm
Created May 24, 2016 01:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save clarketm/a18ac7c2f923699f3e5742c5b76843e5 to your computer and use it in GitHub Desktop.
Save clarketm/a18ac7c2f923699f3e5742c5b76843e5 to your computer and use it in GitHub Desktop.
Find Min Binary Search (JavaSript)
function findMinBinarySearch(array) {
var left = 0, // index of first element
right = array.length - 1, // index of last element.
mid, // midpoint
count = 0;
while (array[left] > array[right]) {
count++;
mid = ~~((left + right) / 2); // math.floor of the midpoint
if (array[mid] > array[right]) {
left = mid + 1;
} else {
right = mid;
}
}
console.log(count + " iterations");
return array[left]; // minimum
}
console.log(findMinBinarySearch([2,3,4,6,7,-4,0])); // min = -4 //=> 3 iterations
console.log(findMinBinarySearch([6,1,2,3,4,5])); // min = 1 //=> 3 iterations
console.log(findMinBinarySearch([2,3,4,0,1,1])); // min = 0 //=> 1 iterations
console.log(findMinBinarySearch([1,1,1,2,0,0])); // min = 0 //=> 3 iterations
console.log(findMinBinarySearch([1,1,1,2,3,3])); // min = 1 //=> 0 iterations
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment