Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.