I've heard about the binary search in an intro class I took a couple months ago, remembered how it worked and read this article, so I attempted to write my first binary search in Python. It works, but when I look at other people's attempts in the article, their code looks cleaner and a bit different.
My two main questions are:
- What can I do to optimize my code from here?
- Am I even performing a true binary search?
def binsearch(mylist, keyval): large = len(mylist)-1 small = 0 temp = (len(mylist)-1)/2 key = 'undefined' flag = 0 while flag == 0: if mylist[small] == keyval: key = small flag = 1 elif mylist[large] == keyval: key = large flag = 1 elif mylist[temp] == keyval: key = temp flag = 1 elif temp + 1 == large or temp -1 == small: flag = 1 if keyval > mylist[temp]: small = temp temp = small + (large - small)/2 elif keyval < mylist[temp]: large = temp temp = temp - (large-small)/2 return key