MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / interpolation_search_by_recursion

Function interpolation_search_by_recursion

searches/interpolation_search.py:76–131  ·  view source on GitHub ↗

Pure implementation of interpolation search algorithm in Python by recursion Be careful collection must be ascending sorted, otherwise result will be unpredictable First recursion should be started with left=0 and right=(len(sorted_collection)-1) Args: sorted_collection: som

(
    sorted_collection: list[int], item: int, left: int = 0, right: int | None = None
)

Source from the content-addressed store, hash-verified

74
75
76def interpolation_search_by_recursion(
77 sorted_collection: list[int], item: int, left: int = 0, right: int | None = None
78) -> int | None:
79 """Pure implementation of interpolation search algorithm in Python by recursion
80 Be careful collection must be ascending sorted, otherwise result will be
81 unpredictable
82 First recursion should be started with left=0 and right=(len(sorted_collection)-1)
83
84 Args:
85 sorted_collection: some sorted collection with comparable items
86 item: item value to search
87 left: left index in collection
88 right: right index in collection
89
90 Returns:
91 index of item in collection or None if item is not present
92
93 Examples:
94 >>> interpolation_search_by_recursion([0, 5, 7, 10, 15], 0)
95 0
96 >>> interpolation_search_by_recursion([0, 5, 7, 10, 15], 15)
97 4
98 >>> interpolation_search_by_recursion([0, 5, 7, 10, 15], 5)
99 1
100 >>> interpolation_search_by_recursion([0, 5, 7, 10, 15], 100) is None
101 True
102 >>> interpolation_search_by_recursion([5, 5, 5, 5, 5], 3) is None
103 True
104 """
105 if right is None:
106 right = len(sorted_collection) - 1
107 # avoid divided by 0 during interpolation
108 if sorted_collection[left] == sorted_collection[right]:
109 if sorted_collection[left] == item:
110 return left
111 return None
112
113 point = left + ((item - sorted_collection[left]) * (right - left)) // (
114 sorted_collection[right] - sorted_collection[left]
115 )
116
117 # out of range check
118 if point < 0 or point >= len(sorted_collection):
119 return None
120
121 if sorted_collection[point] == item:
122 return point
123 if point < left:
124 return interpolation_search_by_recursion(sorted_collection, item, point, left)
125 if point > right:
126 return interpolation_search_by_recursion(sorted_collection, item, right, left)
127 if sorted_collection[point] > item:
128 return interpolation_search_by_recursion(
129 sorted_collection, item, left, point - 1
130 )
131 return interpolation_search_by_recursion(sorted_collection, item, point + 1, right)
132
133

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected