Skip to content

Instantly share code, notes, and snippets.

@firephil
Last active March 5, 2018 22:46
Show Gist options
  • Save firephil/9ea9ecf088907118b792519eb6e512ca to your computer and use it in GitHub Desktop.
Save firephil/9ea9ecf088907118b792519eb6e512ca to your computer and use it in GitHub Desktop.
Binary Search with Iterative and Recursive implementation
def binarySearch(list, item):
first = 0
last = len(list) - 1
if item < list[first] or item > list[last]:
return (item,-1)
while first <= last:
i = (first + last) // 2
if list[i] == item:
return (item,i)
elif list[i] > item:
last = i - 1
elif list[i] < item:
first = i + 1
else:
return (item,-1)
def binarySearchRecursive (list,item):
#simple range check
if item <list[0] or item > list[len(list)-1]:
return (item,-1)
def rec(list, item, start, end):
mid = start + (end - start) // 2
if list[mid] == item:
return (list[mid],mid)
if item < list[mid]:
return rec(list, item, start, mid-1)
if item > list[mid]:
return rec(list ,item, mid+1, end)
return rec(list,item,0,len(list)-1)
def main():
ls = [x for x in range(1,11)]
find = 8
print(ls)
(element,index) = binarySearch(ls, find)
print("Iterative Binary Search | index : %s element: %s" %(index, element))
(element, index) = binarySearchRecursive(ls, find)
print("Recursive Binary Search | index : %s element: %s" % (index, element))
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment