老生常谈的算法了。
#!/usr/bin/python
# -*- coding:utf-8 -*-
# Filename: demo.py
# 用python实现二分查找
def binarySearch(a, ll, rr, val):
while ll <= rr:
mid = int((ll + rr) / 2)
if a[mid] == val:
return mid
elif a[mid] > val:
rr = mid - 1
else:
ll = mid + 1
return -1
if __name__ == '__main__':
a = int(input('请输入要查找的值:'))
flag = binarySearch([1, 2, 3, 4, 5, 6, 7, 8], 0, 7, a)
if flag == -1:
print('数组中不存在%d.' % a)
else:
print('%d的下标是%d.' % (a, flag))
如有不当之处欢迎指出!