Skip to content

Instantly share code, notes, and snippets.

@SteadBytes
Created October 17, 2017 10:32
Show Gist options
  • Save SteadBytes/e658262a4b80d62c9ea097c8086f9179 to your computer and use it in GitHub Desktop.
Save SteadBytes/e658262a4b80d62c9ea097c8086f9179 to your computer and use it in GitHub Desktop.
Binary Search Insert
def binary_search_insert(target, seq):
"""Finds position to insert an item into a **descending** sorted list
Args:
target : value to find insert position of
seq : descending sorted list
Returns:
int: Index of position to insert target to maintain sort
"""
l_index = 0
r_index = len(seq) - 1
if seq[l_index] <= target:
return 0
elif seq[r_index] >= target:
return r_index + 1
else:
result = 0
while r_index >= l_index:
mid = int((l_index + r_index) / 2)
guess = seq[mid]
if guess == target:
return mid
if guess >= target:
l_index = mid + 1
else:
result = mid
r_index = mid - 1
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment