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

2
  • 1
    Well, what's your input? Commented Aug 6, 2017 at 18:41
  • Have a look at this question: Optimize Binary Search Commented Aug 6, 2017 at 18:42

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.