Skip to content

Instantly share code, notes, and snippets.

@Syncrossus
Last active December 6, 2019 16:17
Show Gist options
  • Save Syncrossus/c37494776f9ed641314e1359b16fe296 to your computer and use it in GitHub Desktop.
Save Syncrossus/c37494776f9ed641314e1359b16fe296 to your computer and use it in GitHub Desktop.
A simple function to carry out a dichotomy search (the optimal search for an item's index in a sorted list), because it does not exist in the standard library.
def dichotomy(ls, v, _i=0):
""" Dichotomy search, or the optimal search for an item's index
in a sorted list.
Arguments:
- (list) ls: the list in which to search, must be sorted for
this to work
- v: value to search for in the list, must be comparable to the
items in the list
- (int) _i: should not be used, is reserved for recursive purposes
Returns:
The index of v in ls if found, -1 if not. The value
returned is the first occurrence found, not guaranteed
to be the first in the list
"""
if ls == [] or ls is None:
return -1
midvalue = len(ls) // 2
if v < ls[midvalue]:
return dichotomy(ls[:midvalue], v, _i)
elif v > ls[midvalue]:
return dichotomy(ls[midvalue:], v, _i + midvalue)
else:
return _i + midvalue
@Syncrossus
Copy link
Author

Syncrossus commented Jun 8, 2018

This code is released under the WTFPL.

@Syncrossus
Copy link
Author

As it turns out, python sucks at recursivity so I recommend finding or writing your own iterative implementation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment