Created
April 13, 2014 22:31
-
-
Save uberbrady/10605041 to your computer and use it in GitHub Desktop.
Some tweaks to Oliver Caldwell's excellent binary search Javascript function
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
binaryIndexOf=function (searchElement) { | |
'use strict'; | |
var minIndex = 0; | |
var maxIndex = this.length - 1; | |
var currentIndex; | |
var currentElement; | |
console.warn("WE ARE LOOKING FOR: ",searchElement,"AKA",+searchElement); | |
var circuitbreaker=0; | |
while (minIndex <= maxIndex) { | |
circuitbreaker++; | |
currentIndex = (minIndex + maxIndex) >>1; | |
currentElement = this[currentIndex]; | |
console.warn("minIndex: "+minIndex+" maxIndex: "+maxIndex+" currentIndex: "+currentIndex+" currentElement: "+currentElement); | |
if (currentElement < searchElement) { | |
minIndex = currentIndex+1; | |
} | |
else if (currentElement > searchElement) { | |
maxIndex = currentIndex-1; | |
} | |
else { | |
console.warn("KEY FOUND at: "+currentIndex); | |
return currentIndex; | |
} | |
if(circuitbreaker>32) { | |
console.warn("ERROR. circuitbreaker is: "+circuitbreaker); | |
break; | |
} | |
} | |
console.warn("KEY WAS NEVER FOUND, but it *would* be at: "+currentIndex+" min: "+minIndex+" max: "+maxIndex+". We found: "+currentElement+" at that index, and are looking for "+searchElement); | |
return ~Math.max(minIndex,maxIndex); | |
} |
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
"use strict"; | |
var assert = require("assert"); | |
var bsrch = require ("../search.js"); | |
//requires 'mocha' | |
describe('##binaryIndexOf',function () { | |
var arr=[1,2,3,4,5,6,7]; | |
var fun=function (i) { | |
return bsrch.binaryIndexOf.call(arr,i); | |
}; | |
var fun_assert=function (i,j) { | |
assert.equal(fun(i),j,"Can't find "+i+" (got "+fun(i)+"["+~fun(i)+"], was looking for "+j+"["+~j+"])"); | |
}; | |
it('exact matches should work',function () { | |
fun_assert(1,0); | |
fun_assert(2,1); | |
fun_assert(3,2); | |
fun_assert(4,3); | |
fun_assert(5,4); | |
}); | |
it('mismatches should work',function () { | |
fun_assert(0.5,~0); | |
fun_assert(1.5,~1); | |
fun_assert(2.5,~2); | |
fun_assert(5.5,~5); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment