Created
May 24, 2016 01:31
-
-
Save clarketm/a18ac7c2f923699f3e5742c5b76843e5 to your computer and use it in GitHub Desktop.
Find Min Binary Search (JavaSript)
This file contains 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
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