Created
May 26, 2015 01:09
-
-
Save ruda/f771f64e7ef8a0263b0d 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
# From http://data.linkedin.com/blog/2010/06/beating-binary-search | |
def interpolation_search(key, array, min, max): | |
""" | |
Interpolation search. | |
>>> a = [7, 28, 28, 41, 45, 50, 59, 68, 74, 96] | |
>>> k = 59 | |
>>> print interpolation_search(k, a, 0, 99) | |
6 | |
""" | |
low = 0 | |
high = len(array) - 1 | |
while True: | |
if low > high or key < min or key > max: | |
return -1 | |
if high == low: | |
guess = high; | |
else: | |
size = high - low | |
offset = (size * (key - min)) / (max - min) | |
guess = low + offset | |
if array[guess] == key: | |
return guess | |
if guess == 0 or guess == (len(array) - 1): | |
return -1 | |
if array[guess] > key: | |
high = guess - 1 | |
max = array[guess - 1] | |
else: | |
low = guess + 1 | |
min = array[guess + 1] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment