Skip to content

Commit 4808d62

Browse files
authored
Implemented Exponential Search with binary search for improved performance on large sorted arrays.
1 parent 00e9d86 commit 4808d62

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

searches/Exponential_Search.py

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# Python program to perform Exponential Search
2+
from bisect import bisect_left
3+
4+
# Binary search function
5+
def binary_search(arr, left, right, target):
6+
while left <= right:
7+
mid = left + (right - left) // 2
8+
if arr[mid] == target:
9+
return mid
10+
elif arr[mid] < target:
11+
left = mid + 1
12+
else:
13+
right = mid - 1
14+
return -1
15+
16+
# Exponential search function
17+
def exponential_search(arr, target):
18+
n = len(arr)
19+
20+
# If the target is at the first position
21+
if arr[0] == target:
22+
return 0
23+
24+
# Find the range for binary search by repeatedly doubling the index
25+
i = 1
26+
while i < n and arr[i] <= target:
27+
i *= 2
28+
29+
# Perform binary search within the found range
30+
return binary_search(arr, i // 2, min(i, n - 1), target)
31+
32+
# Example usage
33+
if __name__ == "__main__":
34+
arr = [2, 3, 4, 10, 40, 50, 60, 70, 80, 90, 100]
35+
target = 10
36+
37+
result = exponential_search(arr, target)
38+
39+
if result != -1:
40+
print(f"Element found at index {result}")
41+
else:
42+
print("Element not found in the array")

0 commit comments

Comments
 (0)