File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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" )
You can’t perform that action at this time.
0 commit comments