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.

  1. your naming inconsistent. also, not use list variable name, you're shadowing global builtin.

  2. the stopping condition while low <= high. important.

  3. 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

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -