Skip to content

Instantly share code, notes, and snippets.

@Rahul-Sagore
Created June 9, 2018 22:16
Show Gist options
  • Save Rahul-Sagore/161ac3b9e964dcc8103708594897ce17 to your computer and use it in GitHub Desktop.
Save Rahul-Sagore/161ac3b9e964dcc8103708594897ce17 to your computer and use it in GitHub Desktop.
function binarySearch(arr, findX, leftBound, rightBound) {
if(typeof leftBound == 'undefined') {
var leftBound = 0, rightBound = arr.length;
stepsTaken = 0;
}
var median = Math.ceil((leftBound + rightBound)/2);
console.log("Median Index:", median, "Median Value:", arr[median]);
stepsTaken++;
if(findX == arr[median]) {
console.log("Index of x: ", median)
console.log("Steps taken: ", stepsTaken);
return median;
}
var nextN;
if (findX > arr[median]) {
leftBound = median + 1;
} else {
rightBound = median - 1;
}
console.log("Left: ", leftBound, " Right: ", rightBound);
binarySearch(arr, findX, leftBound, rightBound);
}
// Example
var arr = [2, 5, 8, 11, 13, 15, 17, 19, 21, 23, 27, 29, 31, 35];
binarySearch(arr, 27)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment