Skip to content

Instantly share code, notes, and snippets.

@hdriqi
Last active June 8, 2018 11:50
Show Gist options
  • Save hdriqi/31bea02d10f5227cd9e1b9c621237eab to your computer and use it in GitHub Desktop.
Save hdriqi/31bea02d10f5227cd9e1b9c621237eab to your computer and use it in GitHub Desktop.
Modified binary search to find the nearest value of an array based on the user input.
var kVAStandard = [
900, 1300, 2200, 3500, 4400, 5500, 6600, 7700, 11000, 12000, 13000, 14000, 15000, 16000, 17000, 18000, 19000, 20000, 30000, 50000, 75000, 100000
]
const conquer = (left, right, val)=>{
console.log('conquer', left, right, val)
if(left.length === 1 && right.length === 1){
if(Math.abs(left[0] - val) > Math.abs(right[0] - val)){
console.log('conquer return right', right[0])
return [right[0]]
}
console.log('conquer return left', left[0])
return [left[0]]
}
else{
return conquer(compare(left, val), compare(right, val), val)
}
}
const compare = (arr, val)=>{
console.log('compare', arr, val)
if(val <= arr[0]){
console.log('compare return ' + [arr[0]])
return [arr[0]]
}
else if(val >= arr[arr.length-1]){
console.log('compare return ' + [arr[arr.length-1]])
return [arr[arr.length-1]]
}
else{
const middle = Math.ceil(arr.length / 2)
const left = arr.slice(0, middle)
const right = arr.slice(middle)
return conquer(left, right, val)
}
}
// Find the nearest value in an array with user input (2000)
const result = compare(kVAStandard, 2000)
// Output 2200
console.log(result[0])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment