Here I am trying to implement interpolation search in Python(3.6.1). My logic seems correct but still the output is always giving me False unless I give the first index of the list as the search key. The code follows :
def NSearch(l,n,s):
beg = 0
end = (n-1)
while (beg<=end) and (s>=l[beg]) and (s<=l[end]):
p = beg + int(((float(end - beg) / ( l[end] - l[beg])) * ( s - l[beg])))
if (l[p]==s):
return True
if (l[p]<=s):
beg = p + 1
else:
end = p - 1
return False
liost = [23, 76, 17, -87, 56]
#x = int(input())
x = 76
print(NSearch(liost,len(liost),x))
Read: How-to-debug-small-programs/
I set a breakpoint on your while and looked hard at the values for your example.
# while (beg<=end) and (s>=l[beg]) and (s<=l[end]):
while (0<=4) and (76>=23) and (76<=56): # this is false, function does not enter while.
# all code in while block never executed == irrelevant
return False
Then I looked up interpolation search .
Interpolation search is an algorithm for searching for a given key in an indexed array that has been ordered by numerical values
Then I looked at your inputs:
liost = [23, 76, 17, -87, 56] # not ordered
And fixed them to:
x = 76
print(NSearch(sorted(liost),len(liost),x))
Now if finds it - added couple of other values to check and voila: works.
Sidenote:
print (x in liost) # prints True as well...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.