Created
November 1, 2017 17:04
-
-
Save joshkitt/c63d349c024fe7e607b1d10c32e41544 to your computer and use it in GitHub Desktop.
This file contains 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
function binarySearch(data, search) { | |
// console.log("data", data); | |
var mid = Math.floor(data.length / 2); | |
// console.log('mid', mid) | |
if (data[mid] === search) { | |
// see if mid is what we're looking for | |
return data[mid]; | |
} else if (data.length === 1) { | |
// only one element and does not match | |
return undefined; | |
} else if (search < data[mid]) { | |
return binarySearch(data.slice(0, mid), search) | |
} else if (search > data[mid]) { | |
return binarySearch(data.slice(mid, data.length), search) | |
} else { | |
return undefined; | |
} | |
} | |
var data = [0,1,2,3,4,5,6,8,9]; | |
console.log('using data', data); | |
console.log('find 0', binarySearch(data, 0)); | |
console.log('find 9', binarySearch(data, 9)); | |
console.log('find 10', binarySearch(data, 10)); | |
console.log('find -1', binarySearch(data, -1)); | |
console.log('find 3', binarySearch(data, 3)); | |
console.log('find 4', binarySearch(data, 4)); | |
console.log('find 7', binarySearch(data, 7)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment