Skip to content

Commit 5a911f5

Browse files
committed
Fix out-of-range recursion in interpolation_search_by_recursion
1 parent 7428666 commit 5a911f5

1 file changed

Lines changed: 11 additions & 3 deletions

File tree

searches/interpolation_search.py

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -99,16 +99,24 @@ def interpolation_search_by_recursion(
9999
1
100100
>>> interpolation_search_by_recursion([0, 5, 7, 10, 15], 100) is None
101101
True
102+
>>> interpolation_search_by_recursion([0, 5, 7, 10, 15], 16) is None
103+
True
104+
>>> interpolation_search_by_recursion([0, 5, 7, 10, 15], -1) is None
105+
True
106+
>>> interpolation_search_by_recursion([0, 3, 6, 12, 14, 15, 20], 10) is None
107+
True
108+
>>> interpolation_search_by_recursion([], 1) is None
109+
True
102110
>>> interpolation_search_by_recursion([5, 5, 5, 5, 5], 3) is None
103111
True
104112
"""
105113
if right is None:
106114
right = len(sorted_collection) - 1
115+
if left > right:
116+
return None
107117
# avoid divided by 0 during interpolation
108118
if sorted_collection[left] == sorted_collection[right]:
109-
if sorted_collection[left] == item:
110-
return left
111-
return None
119+
return left if sorted_collection[left] == item else None
112120

113121
point = left + ((item - sorted_collection[left]) * (right - left)) // (
114122
sorted_collection[right] - sorted_collection[left]

0 commit comments

Comments
 (0)