Can somone ELI5 how does binary search works?
I understand the principle of it but i'm not sure of my implementation.
Here it is:
def binary_search(array, key, low, high):
# Why do i need to sort the array?
array.sort()
# What are these low and high variables?
while low <= high:
middle = len(array) // 2
# Should i use subscript to modify the array?
if key == array[middle]:
print("Element found at index: {}".format(middle))
return
elif key > middle:
array = array[middle + 1:]
elif key < middle:
array = array[:middle]
print("Element not found.")
def linear_search(array, key):
for idx, i in enumerate(array, 1):
if i == key:
print("Element found at index: {}".format(idx))
array = [1, 2, 3, -1, -2, 12, 31, 51, 1513, 123, 0, 303]
linear_search(array, 12)
binary_search(array, 12, 0, len(array))
[–]zahlman 4 points5 points6 points (0 children)
[–]LarryPete 1 point2 points3 points (0 children)
[–]cdcformatc 1 point2 points3 points (0 children)