Skip to content

Commit f9d216b

Browse files
committed
interpolation_search code added
1 parent 797ebdb commit f9d216b

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
def interpolation_search(arr, target):
2+
"""
3+
Perform interpolation search to find the target element in a sorted array.
4+
5+
Args:
6+
arr (list): The sorted list to search in.
7+
target (int): The element to search for.
8+
9+
Returns:
10+
int: The index of the target element in the array, or -1 if not found.
11+
"""
12+
left, right = 0, len(arr) - 1
13+
14+
while left <= right and arr[left] <= target <= arr[right]:
15+
if left == right:
16+
if arr[left] == target:
17+
return left
18+
return -1
19+
pos = left + ((target - arr[left]) * (right - left) // (arr[right] - arr[left]))
20+
21+
if arr[pos] == target:
22+
return pos
23+
if arr[pos] < target:
24+
left = pos + 1
25+
else:
26+
right = pos - 1
27+
28+
return -1
29+
30+
if __name__ == "__main__":
31+
32+
# Test case
33+
test_array = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
34+
target_element = 11
35+
result = interpolation_search(test_array, target_element)
36+
37+
if result == -1:
38+
print(f"Element {target_element} is not present in the array")
39+
else:
40+
print(f"Element {target_element} found at position {result} in the array")

0 commit comments

Comments
 (0)