Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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