Last active
February 4, 2019 09:25
-
-
Save meherhowji/37199e781f723fdde7981c338f41c737 to your computer and use it in GitHub Desktop.
Recursive Binary Search in JavaScript
This file contains hidden or 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
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