Skip to content

Instantly share code, notes, and snippets.

@zacacollier
Created May 10, 2017 19:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save zacacollier/b4160e8df451d80e20215506cb143f7f to your computer and use it in GitHub Desktop.
Save zacacollier/b4160e8df451d80e20215506cb143f7f to your computer and use it in GitHub Desktop.
Interpolation Search
/*
* 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