Skip to content

Commit 429154a

Browse files
feat: add Meta Binary Search algorithm in Python
1 parent e2a78d4 commit 429154a

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
def interpolation_search_recursive(arr, low, high, x):
2+
"""Recursive implementation of Interpolation Search."""
3+
if low <= high and arr[low] <= x <= arr[high]:
4+
pos = low + ((high - low) * (x - arr[low])) // (arr[high] - arr[low])
5+
if arr[pos] == x:
6+
return pos
7+
if arr[pos] < x:
8+
return interpolation_search_recursive(arr, pos + 1, high, x)
9+
return interpolation_search_recursive(arr, low, pos - 1, x)
10+
return -1
11+
12+
13+
if __name__ == "__main__":
14+
arr = [10, 20, 30, 40, 50, 60, 70]
15+
x = 50
16+
result = interpolation_search_recursive(arr, 0, len(arr) - 1, x)
17+
print(f"Element {x} found at index: {result}" if result != -1 else "Element not found.")

searches/meta_binary_search.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
def meta_binary_search(arr, target):
2+
"""Meta Binary Search using bit manipulation."""
3+
n = len(arr)
4+
pos = -1
5+
for i in reversed(range(n.bit_length())):
6+
new_pos = pos + (1 << i)
7+
if new_pos < n and arr[new_pos] <= target:
8+
pos = new_pos
9+
if pos != -1 and arr[pos] == target:
10+
return pos
11+
return -1
12+
13+
14+
if __name__ == "__main__":
15+
arr = [2, 5, 7, 9, 14, 18, 21, 25]
16+
target = 18
17+
result = meta_binary_search(arr, target)
18+
print(f"Element {target} found at index: {result}" if result != -1 else "Element not found.")

0 commit comments

Comments
 (0)