二进制搜索Python实现

时间:2017-08-06 18:37:46

标签: python binary-search recursive-datastructures

我正在尝试在python中实现递归二进制搜索。我想将数组和元素作为用户的输入进行搜索。如果找到该元素,程序应该打印实际的元素,而不是它的索引到控制台。我真的很感激任何建议/修改 感谢

这是我的代码:

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

这是输出:

Line 7: IndexError: list index out of range

另外,我想使用raw_input从用户那里获取输入,而不是在函数调用中提供输入。结果不应该是元素的索引而是实际的元素本身

0 个答案:

没有答案