I have a list with numbers from 0-9:
mylist = list(range(10))
I am getting an error with the division command to get mid
:
def binary_search(mylist, element, low, high):
low=0
high= len(mylist)
mid=low + (high- mymin)/2
if mid==len(mylist):
return False
elif mylist[mid]==element:
return mid
elif high==low:
return False
elif mylist[mid]<element:
return binary_search(mylist, element, mymin, mid-1)
elif mylist[mid]<element:
return binary_search(mylist, element, mid+1, mymax)
else:
return mid
and if I wanted to return True
how would I write that on top of return binary_search(mylist, element, mymin, mid-1)
?
We split a collection of items into two halves in Binary Search to decrease the number of direct comparisons needed to discover an element. However, there's one requirement: the array's items must be sorted beforehand.
Binary search is a recursive algorithm. The high level approach is that we examine the middle element of the list. The value of the middle element determines whether to terminate the algorithm (found the key), recursively search the left half of the list, or recursively search the right half of the list.
The binary search algorithm can be written either iteratively or recursively. Data must be in sorted order to use the binary search algorithm.
A recursive algorithm to search for a key in a BST follows immediately from the recursive structure: If the tree is empty, we have a search miss; if the search key is equal to the key at the root, we have a search hit. Otherwise, we search (recursively) in the appropriate subtree.
`Please correct me if I am wrong as I am a new programmer but here is my solution:
def binary_search(test_cases, item_to_be_found):
try:
if item_to_be_found == test_cases[len(test_cases) // 2]:
return True
elif item_to_be_found < test_cases[len(test_cases) // 2]:
test_cases = test_cases[:len(test_cases) // 2]
else:
test_cases = test_cases[len(test_cases) // 2:]
return binary_search(test_cases, item_to_be_found)
except RecursionError:
return False
please correct me, if the code presents any bugs
def binary_recursive(array, val):
if val < array[0] or val > array[-1]:
return False
mid = len(array) // 2
left = array[:mid]
right = array[mid:]
if val == array[mid]:
return True
elif array[mid] > val:
return binary_recursive(left, val)
elif array[mid] < val:
return binary_recursive(right, val)
else:
return False
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With