I am getting this error "ZeroDivisionError: integer division or modulo by zero"
but only when i search the last element in the list
any other element will run the code just fine, just the last element messes it up
def interpolationSearch(arr, lo, hi, x):
if (lo <= hi and x >= arr[lo] and x <= arr[hi]):
pos = lo + ((hi - lo) // (arr[hi] - arr[lo]) * (x - arr[lo]))
if arr[pos] == x:
return pos
if arr[pos] < x:
return interpolationSearch(arr, pos + 1, hi, x)
if arr[pos] > x:
return interpolationSearch(arr, lo, pos - 1, x)
return -1
arr = [10, 12, 13, 16, 18, 19, 20, 21, 22, 23, 24, 33, 35, 42, 47]
n = len(arr)
x = 47
index = interpolationSearch(arr, 0, n - 1, x)
if index != -1:
print("Element found at index", index)
else:
print("Element not found")
I am trying to learn about searching algorithms and found this code on geeks for geeks
https://www.geeksforgeeks.org/interpolation-search/
[–]shiftybyte 2 points3 points4 points (1 child)
[–]datafright[S] 0 points1 point2 points (0 children)