Created
May 2, 2018 16:20
-
-
Save SharanSMenon/92414242d5c0f3f8536aacd3c4d04e60 to your computer and use it in GitHub Desktop.
Implements the binary search
algorithm in Python 3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def sort(l): | |
""" | |
Sorts a list | |
:param l: | |
:return: l_sorted | |
""" | |
l_copy = l.copy() | |
l_sorted = [] | |
for i in range(0, len(l_copy)): | |
minimum = reduce(min, l_copy) | |
# print(minumum) | |
l_sorted.append(minimum) | |
l_copy.remove(minimum) | |
return l_sorted | |
def binary_search(list_, key, low=0, high=0): | |
""" | |
Uses the binary search method to search through a sorted ist | |
Returns -1 if not found | |
:param list_: list | |
:param key: integer | |
:param low: integer | |
:param high: length of list_ | |
:return: an index i or -1 | |
""" | |
if high < low: | |
return low-1 | |
if high == 0: | |
high = len(list_) | |
mid = low + int(((high - low) / 2)) | |
try: | |
_ = list_[mid] | |
except IndexError: | |
return -1 | |
if key == list_[mid]: | |
return mid | |
elif key < list_[mid]: | |
return binary_search(list_, key, high=mid - 1, low=low) | |
else: | |
return binary_search(list_, key, low=mid + 1, high=high) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment