Binary Search implementation in Python -
i trying implement solution using binary search. have list of numbers
list = [1, 2, 3, 4, 6] value searched = 2
i have written this
def searchbinary(list, sval): low = 0 high = len(list) while low < high: mid = low + math.floor((high - low) / 2) if list[mid] == sval: print("found : ", sval) elif l2s[mid] > sval: high = mid - 1 else: low = mid + 1
but when trying implement this, getting error like: index out of range. please in identifying issue.
a few things.
your naming inconsistent. also, not use
list
variable name, you're shadowing global builtin.the stopping condition
while low <= high
. important.you not break when find value. result in infinite recursion.
def searchbinary(l2s, sval): # not use 'list' variable low = 0 high = len(l2s) while low <= high: # main issue. long low not greater high, while loop must run mid = low + math.floor((high - low) / 2) if l2s[mid] == sval: print("found : ", sval) return elif l2s[mid] > sval: high = mid - 1 else: low = mid + 1
and now,
list_ = [1, 2, 3, 4, 6] searchbinary(list_, 2)
output:
found : 2
Comments
Post a Comment