Skip to content

Instantly share code, notes, and snippets.

@meherhowji
Last active February 4, 2019 09:25
Show Gist options
  • Save meherhowji/37199e781f723fdde7981c338f41c737 to your computer and use it in GitHub Desktop.
Save meherhowji/37199e781f723fdde7981c338f41c737 to your computer and use it in GitHub Desktop.
Recursive Binary Search in JavaScript
sortedList = [11, 24, 33, 64, 95, 106, 217, 228, 299, 310]
const getMid = (low, high) => {
return Math.floor((high + low) / 2)
}
const recursiveBS = (list, item, low, high) => {
(!low && !high ) && (low = 0, high = list.length - 1)
let found = false
if (low <= high) {
let mid = getMid(low, high)
, guess = list[mid]
if (guess === item) {
console.log ("Your item is at " + (getMid(low, high) + 1) + " position")
} else if (guess > item) {
recursiveBS(list, item, low, mid - 1)
} else {
recursiveBS(list, item, mid + 1, high)
}
}
}
recursiveBS(sortedList, 217)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment