Javascript Array binarySearchRecurse(target)
Array.prototype.binarySearchRecurse = function(target) { var half = Math.floor(this.length/2); if (target === this[half]) { return half;/* w ww . ja va 2 s . c om*/ } else if (this.length === 1) { return null; } if (target > this[half]) { return this.splice(half, this.length).binarySearchRecurse(target); } else { return this.splice(0, half).binarySearchRecurse(target); } };
Array.prototype.binarySearchRecurse = function(val) { var initArray = this.slice(); var result;/* w w w .j av a 2s. c o m*/ var recurse = function(firstHalf) { if (firstHalf.length === 1) { result = firstHalf[0] === val; return; } var arrayHalfIndex = Math.floor(firstHalf.length/2); var secondHalf = firstHalf.splice(arrayHalfIndex, firstHalf.length - 1); if (val < secondHalf[0]) { if (firstHalf[0] === val) { result = true return; } recurse(firstHalf); } else { if (secondHalf[0] === val) { result = true; return; } recurse(secondHalf); } } recurse(initArray); return result; }; //val = 3 //[1,2,3,4,5] // [1,2,3] & [4,5] //val < [4,5][0] === true //call recursion with firstHalf //[1] & [2,3] //val < [2,3][0] === false //call recursion with secondHalf //[3] & [2] //val === [2][0] // var firstHalf = this.slice(); // var secondHalf;