Binary Search Implementation In Python
I am trying to implement a solution using binary search. I have a list of numbers list = [1, 2, 3, 4, 6] value to be searched = 2 I have written something like this def searchBina
Solution 1:
A few things.
Your naming is inconsistent. Also, do not use
list
as a variable name, you're shadowing the global builtin.The stopping condition is
while low <= high
. This is important.You do not break when you find a value. This will result in infinite recursion.
def searchBinary(l2s, sval): # do not use 'list'as a variable
low = 0
high = len(l2s)
while low <= high: # thisis the main issue. As long as low is not greater than high, the while loop must run
mid = (high + low) // 2if l2s[mid] == sval:
print("found : ", sval)
return
elif l2s[mid] > sval:
high = mid - 1else:
low = mid + 1
And now,
list_ = [1, 2, 3, 4, 6]
searchBinary(list_, 2)
Output:
found :2
Solution 2:
UPDATEhigh = len(lst) - 1
per comments below.
Three issues:
- You used
l2s
instead oflist
(the actual name of the parameter). - Your
while
condition should below <= high
, notlow < high
. - You should presumably return the index when the value is found, or
None
(or perhaps -1?) if it's not found.
A couple other small changes I made:
- It's a bad idea to hide the built-in
list
. I renamed the parameter tolst
, which is commonly used in Python in this situation. mid = (low + high) // 2
is a simpler form of finding the midpoint.- Python convention is to use snake_case, not camelCase, so I renamed the function.
Fixed code:
defbinary_search(lst, sval):
low = 0
high = len(lst) - 1while low <= high:
mid = (low + high) // 2if lst[mid] == sval:
return mid
elif lst[mid] > sval:
high = mid - 1else:
low = mid + 1returnNoneprint(binary_search([1, 2, 3, 4, 6], 2)) # 1
Post a Comment for "Binary Search Implementation In Python"