1
- # Python program to perform Exponential Search
2
- from bisect import bisect_left
1
+ from typing import List
3
2
3
+ def binary_search (arr : List [int ], left : int , right : int , target : int ) -> int :
4
+ """
5
+ Perform binary search on a sorted array.
4
6
5
- # Binary search function
6
- def binary_search (arr , left , right , target ):
7
+ Parameters:
8
+ arr (List[int]): The sorted list in which to search.
9
+ left (int): The starting index for the search range.
10
+ right (int): The ending index for the search range.
11
+ target (int): The value to search for.
12
+
13
+ Returns:
14
+ int: The index of the target if found, otherwise -1.
15
+
16
+ Doctest:
17
+ >>> binary_search([2, 3, 4, 10, 40], 0, 4, 10)
18
+ 3
19
+ >>> binary_search([2, 3, 4, 10, 40], 0, 4, 5)
20
+ -1
21
+ """
7
22
while left <= right :
8
23
mid = left + (right - left ) // 2
9
24
if arr [mid ] == target :
@@ -15,8 +30,27 @@ def binary_search(arr, left, right, target):
15
30
return - 1
16
31
17
32
18
- # Exponential search function
19
- def exponential_search (arr , target ):
33
+ def exponential_search (arr : List [int ], target : int ) -> int :
34
+ """
35
+ Perform exponential search on a sorted array.
36
+
37
+ Exponential search first finds a range where the target may reside
38
+ by repeatedly doubling the index. It then performs binary search
39
+ within that range.
40
+
41
+ Parameters:
42
+ arr (List[int]): The sorted list in which to search.
43
+ target (int): The value to search for.
44
+
45
+ Returns:
46
+ int: The index of the target if found, otherwise -1.
47
+
48
+ Doctest:
49
+ >>> exponential_search([2, 3, 4, 10, 40, 50, 60, 70, 80, 90, 100], 10)
50
+ 3
51
+ >>> exponential_search([2, 3, 4, 10, 40, 50, 60, 70, 80, 90, 100], 5)
52
+ -1
53
+ """
20
54
n = len (arr )
21
55
22
56
# If the target is at the first position
@@ -32,8 +66,10 @@ def exponential_search(arr, target):
32
66
return binary_search (arr , i // 2 , min (i , n - 1 ), target )
33
67
34
68
35
- # Example usage
36
69
if __name__ == "__main__" :
70
+ """
71
+ Example to demonstrate the usage of exponential_search function.
72
+ """
37
73
arr = [2 , 3 , 4 , 10 , 40 , 50 , 60 , 70 , 80 , 90 , 100 ]
38
74
target = 10
39
75
0 commit comments