Skip to content

Commit

Permalink
Merge pull request #141 from tinyCodersDen/main
Browse files Browse the repository at this point in the history
Added Interpolation Search Program using Python
  • Loading branch information
Anjan50 authored Oct 21, 2023
2 parents b602a15 + eb68a0e commit a238ffd
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions Searching/InterpolationSearch.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Python Implementation for Interpolation Search Algorithm:

def interpolationSearch(arr, lo, hi, x):

# The target must be in range defined by the corner:
if (lo <= hi and x >= arr[lo] and x <= arr[hi]):

# Probing position(uniform distance):
pos = lo + ((hi - lo) // (arr[hi] - arr[lo]) * (x - arr[lo]))

# Target found:
if arr[pos] == x:
return pos

# If target is larger, it's in right subarray:
if arr[pos] < x:
return interpolationSearch(arr, pos + 1,hi, x)

# If target is smaller, it's in left subarray:
if arr[pos] > x:
return interpolationSearch(arr, lo, pos - 1, x)
return -1

# Array of sorted items:
arr = [10, 21, 35, 47, 52, 58, 76, 81, 92, 96]

# Element to be searched
target = 35
index = interpolationSearch(arr, 0, len(arr) - 1, target)

# Checking if the element is found or not:
if index != -1:
print("Element found at index", index)
else:
print("Element not found")

0 comments on commit a238ffd

Please sign in to comment.