def get_arr_elem(arr: [], key: int): arr_len = len(arr) def find_pivot(low, high): if low > high: return mid = (low + high) // 2 if mid > low and arr[mid] < arr[ mid - 1]: # mid > low is required to avoid error, if low=high=0 return mid - 1 if mid < high and arr[mid] > arr[ mid + 1]: # mid < high is required to avoid error, if low=high=len(arr) - 1 return mid if arr[mid] <= arr[low]: return find_pivot(low, mid - 1) return find_pivot(mid + 1, high) pivoted_index = find_pivot(0, arr_len - 1) if pivoted_index: if arr[pivoted_index] == key: return pivoted_index if key > arr[0]: return binary_search(arr, 0, pivoted_index - 1, key) return binary_search(arr, pivoted_index + 1, arr_len - 1, key) return binary_search(arr, 0, arr_len - 1, key)
def get_elem_index_in_infinite_stream(stream: [], num: int): k = 0 end_index = 0 while stream[end_index] < num: k += 1 end_index = 1 << k return binary_search(stream, end_index >> 1, end_index, num)
def _get_arr_elem(low, high): if high < low: return mid = (low + high) // 2 if arr[mid] == key: return mid # if arr[low:mid + 1] is sorted if arr[mid] >= arr[low]: if arr[mid] > key and arr[low] <= key: return binary_search(arr, low, mid - 1, key) return _get_arr_elem(mid + 1, high) # arr[mid + 1:] is sorted else: if arr[mid + 1] <= key and arr[high] >= key: return binary_search(arr, mid + 1, high, key) return _get_arr_elem(low, mid - 1)
def test_binary_search_not_in_list_small(): input_array = [1, 5, 10] target = -100 assert arrays.binary_search(input_array, target) == -1
def test_binary_search_last_in_list(): input_array = [1, 5, 10] target = 10 assert arrays.binary_search(input_array, target) == 2
def test_binary_search_odd_list(): input_array = [1, 5, 10] target = 1 assert arrays.binary_search(input_array, target) == 0
def test_binary_search_even_list(): input_array = [1, 4, 8, 10] target = 4 assert arrays.binary_search(input_array, target) == 1
def test_binary_search_short_list_not_found(): input_array = [1] target = 10 assert arrays.binary_search(input_array, target) == -1
def test_binary_search_no_list(): input_array = [] target = 1 assert arrays.binary_search(input_array, target) == -1