Skip to content

Instantly share code, notes, and snippets.

@ti-ka
Last active January 31, 2018 19:25
Show Gist options
  • Save ti-ka/24c5fb6720d953150efd71dad437e2fa to your computer and use it in GitHub Desktop.
Save ti-ka/24c5fb6720d953150efd71dad437e2fa to your computer and use it in GitHub Desktop.
Binary search on a sorted array using recursion: https://jsbin.com/pilitor/edit?js,console
// Task:
// Find an item in an sorted array.
var array = [1,3,4,6,7,8,8,9,10,56,102,200,230]
var item = 200
var globalCounter = 0
console.log(binarySearch(array, item))
console.log("iterated " + globalCounter + " time/s.")
function binarySearch(array, item, leftIndex, rightIndex) {
// Count "O"
globalCounter++
if (leftIndex === undefined) leftIndex = 0;
if (rightIndex === undefined) rightIndex = array.length - 1;
var midIndex = leftIndex + Math.floor((rightIndex - leftIndex) / 2);
if (leftIndex > rightIndex) {
return false;
}
if (array[midIndex] === item) {
return true;
} else if (item < array[midIndex]) {
return binarySearch(array, item, leftIndex, midIndex - 1);
} else {
return binarySearch(array, item, midIndex + 1, rightIndex);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment