Skip to content

Instantly share code, notes, and snippets.

@jainal09
Created April 1, 2023 23:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jainal09/6022a1e3cf4356fcb7e4b2993f851889 to your computer and use it in GitHub Desktop.
Save jainal09/6022a1e3cf4356fcb7e4b2993f851889 to your computer and use it in GitHub Desktop.
Order Agnostic Binary Search in Python
import random
def search_array(array, target):
start_index = 0
end_index = len(array) - 1
is_ascending = array[start_index] < array[end_index]
while start_index <= end_index:
mid_index = start_index + (end_index - start_index) // 2
if target == array[mid_index]:
return mid_index
if is_ascending:
if target < array[mid_index]:
end_index = mid_index - 1
else:
start_index = mid_index + 1
else:
if target < array[mid_index]:
start_index = mid_index + 1
else:
end_index = mid_index - 1
return -1
if __name__ == '__main__':
nums1 = [-1, 2, 4, 6, 7, 8, 12, 15, 19, 32, 45, 67, 99]
nums2 = [99, 67, 45, 32, 19, 15, 12, 8, 7, 6, 4, 2, -1]
target = -1
print(search_array(nums1, target))
print(search_array(nums2, target))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment