0

I am trying to implement a recursive Binary search in python. I want to take the array and element to be searched as input from the user. if the element is found, the program should print the actual element, and not its index to the console. I'd really appreciate any suggestions/modifications thanks

Here is my code:

def Binarysearch(a, low, high, x):
    if low > high:
        return -1
    mid = (low + high)/2
    if x == a[mid]:
        return mid
    elif x < a[mid]:
        return Binarysearch(a, low, mid - 1, x)
    else:
        return Binarysearch(a, mid +1, high, x)


a = int(raw_input('Enter how many elements you want in the list'))

n = len(range(a))
elem_list = []
for i in range(n):
    elem = int(raw_input('enter element'))
    elem_list.append(elem)           

x = int(raw_input('enter search elemet'))           

result = Binarysearch(elem_list, 0, n-1, x)

if result == -1:
    print "Not found"
else:
    print "Found it", x

Here is the output:

Line 7: IndexError: list index out of range

Also, I want to take input from the user using raw_input and not provide input in function call. The result should not be index of the element but the actual element itself

suyash gautam
  • 169
  • 1
  • 2
  • 9
  • 1
    Well, what's your input? – cs95 Aug 06 '17 at 18:41
  • Have a look at this question: [Optimize Binary Search](https://stackoverflow.com/questions/44858843/optimize-binary-search/44859478#44859478) – GIZ Aug 06 '17 at 18:42

0 Answers0