There are two problems, both of them are on the last line:
def binary(n, target):
n.sort()
mid = (0 + (len(n) - 1)) // 2
if target == n[mid]:
return mid
elif target < n[mid]:
return binary(n[:mid], target)
elif target > n[mid]:
return mid + 1 + binary(n[mid + 1:],target)
^^^^^^^^ ^
- since you're slicing, and in order to provide the index in the original sorted list, we need to keep track of the indexes we "lose" while recursing
- The complete to
n[:mid] is n[mid+1:] - not n[mid:] because you already checked the target (in mid) and want to remove it from future iterations - this is, by the way, what causes the infinite loop!
Since we slice the list at mid+1 we need to add mid+1 before calling recursively, in order to preserve the index of the item on the right-side of the list:
[1,2,3,4,5]
^ say we slice here and get [4,5]
we want to save the indexes so we'll add mid (2) + 1 since now in [4,5] the item 4 will get the index zero
Comment: by calling n.sort() upon every iteration we "lose" all the advantage of binary search since, even after the list is sorted, to re-sort it will take at least O(n). So if we need to sort first, we might as well just iterate the array until the item is found/not-found. Or, if we insist on sorting, do it only once and only then call recursively:
n.sort()
binary(n, 2)
where binary does't include the sorting anymore:
def binary(n, target):
mid = (0 + (len(n) - 1)) // 2
if target == n[mid]:
return mid
elif target < n[mid]:
return binary(n[:mid], target)
elif target > n[mid]:
return mid + 1 + binary(n[mid + 1:], target)
nandmidto see what is going on? Also, you're unnecessarily sorting your list (segment) many times. I'm assuming mid becomes 0.