Skip to content

Commit ebe0046

Browse files
committed
Added search in a rotated sorted array in searches
1 parent a71618f commit ebe0046

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
def search_in_rotated_sorted_array(nums: list[int], target: int) -> int:
2+
"""
3+
Search for a target value in a rotated sorted array.
4+
5+
This function implements a modified binary search to find the index of a target
6+
value in an array that was originally sorted in ascending order but then rotated
7+
at some pivot point unknown to you beforehand.
8+
9+
Args:
10+
nums: A list of integers that is sorted in ascending order and then rotated
11+
at some pivot point. Example: [4, 5, 6, 7, 0, 1, 2]
12+
target: The integer value to search for in the array.
13+
14+
Returns:
15+
int: The index of target in nums if found, otherwise -1.
16+
17+
Raises:
18+
ValueError: If nums is empty.
19+
20+
Examples:
21+
>>> search_in_rotated_sorted_array([4, 5, 6, 7, 0, 1, 2], 0)
22+
4
23+
>>> search_in_rotated_sorted_array([4, 5, 6, 7, 0, 1, 2], 3)
24+
-1
25+
>>> search_in_rotated_sorted_array([1], 0)
26+
-1
27+
>>> search_in_rotated_sorted_array([1], 1)
28+
0
29+
>>> search_in_rotated_sorted_array([], 1)
30+
Traceback (most recent call last):
31+
...
32+
ValueError: nums cannot be empty
33+
"""
34+
if not nums:
35+
raise ValueError("nums cannot be empty")
36+
37+
left_index, right_index = 0, len(nums) - 1
38+
39+
while left_index <= right_index:
40+
middle_index = (left_index + right_index) // 2
41+
42+
if nums[middle_index] == target:
43+
return middle_index
44+
45+
# Check if left half is sorted
46+
if nums[left_index] <= nums[middle_index]:
47+
# Target is in the sorted left half
48+
if nums[left_index] <= target < nums[middle_index]:
49+
right_index = middle_index - 1
50+
else:
51+
left_index = middle_index + 1
52+
# Right half is sorted
53+
elif nums[middle_index] < target <= nums[right_index]:
54+
left_index = middle_index + 1
55+
else:
56+
right_index = middle_index - 1
57+
58+
return -1
59+
60+
61+
if __name__ == "__main__":
62+
import doctest
63+
64+
doctest.testmod()
65+
66+
# Additional test cases
67+
test_cases = [
68+
([4, 5, 6, 7, 0, 1, 2], 0),
69+
([4, 5, 6, 7, 0, 1, 2], 3),
70+
([1], 0),
71+
([1], 1),
72+
([3, 1], 1),
73+
([3, 1], 3),
74+
]
75+
76+
for nums, target in test_cases:
77+
result = search_in_rotated_sorted_array(nums, target)
78+
print(f"search_in_rotated_sorted_array({nums}, {target}) = {result}")

0 commit comments

Comments
 (0)