Wrote this to try my hands a building a Binary Search. It is by no means the most refactored code there is but wondering why everything works except when X is the last value in the array (i.e. x = 77)?
function binary_search(x, arr) {
var len = arr.length - 1 //because index starts at 0
var min = arr[0]
var max = arr[0]
var new_arr = []
if(x < arr[0] || x > arr[len])
//console.log(arr[len])
console.log (x + " is not within array range.")
else
find_x(x, arr)
function find_x(x, arr) {
var mid = Math.floor(arr.length/2) //takes care of odd numbered elements in array
if (x === arr[mid])
console.log("Found " + x)
else if(x < arr[mid])
{
max = arr[mid]
new_arr = arr.slice(0, mid)
find_x(x, new_arr)
}
else if(x > arr[mid])
{
min = arr[mid]
new_arr = arr.slice(mid, len)
find_x(x, new_arr)
}
else
console.log(x + " is not in array.")
}
}
var arr = [1,12,43,55,66,77]
binary_search(77, arr)
console.log('x=',x,'arr=',arr);as the first line of thefind_xfunction and you shall be illuminated.findfunction only used its scoped variables. Check oli.me.uk/2013/06/08/… as an example of a better implementation