Skip to content

Commit 70cf2de

Browse files
authored
Merge pull request #31 from Aviral1-jain/patch-2
Create interpolation_search.py
2 parents 788205c + 1859aaa commit 70cf2de

1 file changed

Lines changed: 33 additions & 0 deletions

File tree

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import math
2+
3+
def interpolation_search(arr, target):
4+
"""
5+
Perform interpolation search to find the target value in the given sorted list.
6+
7+
Parameters:
8+
arr (list): The sorted list to be searched.
9+
target: The value to be searched for.
10+
11+
Returns:
12+
int: The index of the target value if found, otherwise -1.
13+
"""
14+
low = 0
15+
high = len(arr) - 1
16+
while low <= high and target >= arr[low] and target <= arr[high]:
17+
pos = low + ((high - low) // (arr[high] - arr[low])) * (target - arr[low])
18+
if arr[pos] == target:
19+
return pos
20+
elif arr[pos] < target:
21+
low = pos + 1
22+
else:
23+
high = pos - 1
24+
return -1
25+
26+
# Example usage:
27+
arr = [2, 3, 4, 10, 40]
28+
target = 10
29+
result = interpolation_search(sorted(arr), target)
30+
if result != -1:
31+
print(f"Interpolation Search: Element found at index {result}")
32+
else:
33+
print("Interpolation Search: Element not found")

0 commit comments

Comments
 (0)