Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions searches/rotated_binary_search.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
def rotated_binary_search(arr: list[int], key: int) -> int:

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As there is no test file in this pull request nor any test function or class in the file searches/rotated_binary_search.py, please provide doctest for the function rotated_binary_search

"""
Performs binary search on a rotated sorted list.

Parameters:
arr (list[int]): A rotated sorted list of integers.
key (int): The element to search for.

Returns:
int: The index of the key in the list, or -1 if the key is not found.
"""
low = 0
high = len(arr) - 1

while low <= high:
mid = (low + high) // 2

# Check if the mid element is the key
if arr[mid] == key:
return mid

# Check which side is sorted
if arr[low] <= arr[mid]: # Left side is sorted
if arr[low] <= key < arr[mid]: # Key is in the sorted left side
high = mid - 1
else: # Key is in the right side
low = mid + 1
else: # Right side is sorted
if arr[mid] < key <= arr[high]: # Key is in the sorted right side

Check failure on line 29 in searches/rotated_binary_search.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (PLR5501)

searches/rotated_binary_search.py:28:9: PLR5501 Use `elif` instead of `else` then `if`, to reduce indentation

Check failure on line 29 in searches/rotated_binary_search.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (PLR5501)

searches/rotated_binary_search.py:28:9: PLR5501 Use `elif` instead of `else` then `if`, to reduce indentation

Check failure on line 29 in searches/rotated_binary_search.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (PLR5501)

searches/rotated_binary_search.py:28:9: PLR5501 Use `elif` instead of `else` then `if`, to reduce indentation
low = mid + 1
else: # Key is in the left side
high = mid - 1

return -1 # Key not found
Loading