Created
May 10, 2017 19:37
-
-
Save zacacollier/b4160e8df451d80e20215506cb143f7f to your computer and use it in GitHub Desktop.
Interpolation Search
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
/* | |
* Performance Test at | |
* https://jsperf.com/interpolate-search/1 | |
*/ | |
"use strict"; | |
function interpolateSearch(array, target) { | |
var high = array.length - 1; | |
var low = 0; // lowest possible index of an array is 0 | |
var maxValue = array[array.length - 1]; | |
var minValue = array[0]; | |
var range = maxValue - minValue; | |
/* Point-Slope Formula: | |
* | |
* y = m(x - x1) + y1 | |
* refactored to be | |
* y = ((y2 - y1) / (x2 - x1)) * (x - x1) + y1 | |
* | |
*/ | |
var index = high / range * (target - minValue) + low; | |
if (index) { | |
return index; | |
} else { | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment