刚看到一篇博客说现在90%的程序员都无法正确的写出二分法查找,吓得我赶紧试了试
#python code
def binary_serach(arr,st,end,tar): mid = st + end mid = mid // 2 if st > end: return False elif tar == arr[mid]: return True elif tar < arr[st] or tar > arr[end]: return False elif tar < arr[mid]: return binary_serach(arr,st,mid,tar) elif tar > arr[mid]: return binary_serach(arr,mid+1,end,tar) else: return False if __name__ == "__main__": l = [1,3,5,6,8,9,12,15,17,23,45] print(l) print("target: %s, result: %s" % (0, binary_serach(l, 0, len(l) - 1, 0))) print("target: %s, result: %s" % (1, binary_serach(l, 0, len(l) - 1, 1))) print("target: %s, result: %s" % (2, binary_serach(l, 0, len(l) - 1, 2))) print("target: %s, result: %s" % (3, binary_serach(l, 0, len(l) - 1, 3))) print("target: %s, result: %s" % (23, binary_serach(l, 0, len(l) - 1, 23))) print("target: %s, result: %s" % (45, binary_serach(l, 0, len(l) - 1, 45))) print("target: %s, result: %s" % (46, binary_serach(l, 0, len(l) - 1, 46)))
下面是测试结果
那么我还没忘
技术发展那么快,一次又一次的迭代,到头来发现,还是颈椎病对我们不离不弃。
活动脖子,天天code
那么今天就愉快的下班了吧
黑夜给了我黑色的眼睛,我却用它寻找光明