chore(Python): added interpolation search file (#334)

pull/335/head^2
RobHam 2021-06-04 16:02:02 +01:00 committed by GitHub
parent 5b028ab3c3
commit cd476b055e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 51 additions and 6 deletions

View File

@ -21,6 +21,7 @@
2. [Jump Search](searching/jump_search.py)
3. [Linear Search](searching/linear_search.py)
4. [Ternary Search](searching/ternary_search.py)
5. [Interpolation Search](searching/interpolation_search.py)
## Sorting
1. [Bubble Sort](sorting/bubble_sort.py)
@ -44,4 +45,3 @@
1. [Print Fibonacci Series Up To N-th Term](dynamic_programming/fibonacci_series.py)
2. [Sum Up To N-th Term Of Fibonacci Series](dynamic_programming/fibonacci_series_sum.py )
3. [N-th Term Of Fibonacci Series](dynamic_programming/fibonacci_series_nth_term.py)

View File

@ -0,0 +1,45 @@
def interpolation_search(array, x):
"""
Use interpolation search to find a specified integer
"""
if isinstance(x, int) and isinstance(array, list): # check that x is integer and array is list
if len(array) < 1: # if array length is less than 1 print message
return False
elif len(array) == 1 and x in array: # if x is only element of array return index 0
return 0
elif len(array) > 1 and x in array: # search if array length > 1 and x is in the array
min = 0
max = len(array) - 1
while min <= max:
if array[min] == array[max] == x:
return min
elif array[min] == array[max] != x:
return False
else:
p = int(min + (x-array[min])*(max-min) / (array[max]-array[min]))
if array[p] == x:
return p
elif x < array[p]:
max = p - 1
continue
elif x > array[p]:
min = p + 1
continue
else:
return False # if x is not in array return false
else:
raise Exception('Please make sure x is an integer and array is a list.')
if __name__ == '__main__':
tests = [
([1,4,7,10,13,16], 13),
([1,4,7,10,13,16], 11),
([1,1,1,1,1,1], 1),
([0,0,0,1,1,1,1,1,1,2,3,4,5], 1),
([24], 24),
([], 24)
]
for test in tests:
print(interpolation_search(test[0], test[1]))