/ Published in: JavaScript
Released into the public domain.
Expand |
Embed | Plain Text
function binarySearch(needleValue, arrayHaystack) { var lowerBound, upperBound, midpointIndex, midpointValue; lowerBound = 0; upperBound = arrayHaystack.length - 1; midpointIndex = Math.ceil((upperBound+lowerBound)/2); midpointValue = arrayHaystack[midpointIndex]; while(midpointIndex>=0&&midpointIndex<arrayHaystack.length&&midpointValue!=needleValue) { if(arrayHaystack[lowerBound]==needleValue) { midpointIndex = lowerBound; midpointValue = arrayHaystack[midpointIndex]; break; } else if(arrayHaystack[upperBound]==needleValue) { midpointIndex = upperBound; midpointValue = arrayHaystack[midpointIndex]; break; } else { midpointIndex = Math.ceil((upperBound+lowerBound)/2); midpointValue = arrayHaystack[midpointIndex]; if(needleValue>midpointValue) // in the second half lowerBound = midpointIndex + 1; else if(needleValue<midpointValue) // in the first half upperBound = midpointIndex - 1; } midpointValue = arrayHaystack[midpointIndex]; if(lowerBound>upperBound) { midpointValue = undefined; break; } } arrayHaystack = null; lowerBound = null; upperBound = null; if(typeof midpointValue=='undefined') { midpointIndex = null; midpointValue = null; return -1; // not found } else { midpointValue = null; return midpointIndex; // found at arrayHaystack[midpointIndex] } }
You need to login to post a comment.
