二分查找

来源:互联网 发布:php全站搜索 编辑:程序博客网 时间:2024/06/07 13:51
#!/usr/bin/env python3# -*- coding: utf-8 -*-' a test module '__author__ = 'Zhang Shuai'a = [2, 34, 45, 56, 57, 68, 78, 82, 86, 90]def binary_search(a, x, i, j):    if i > j:        return "don't find"    tmp = (i + j) // 2    if x < a[tmp]:        return binary_search(a, x, i, tmp - 1)    elif x > a[tmp]:        return binary_search(a, x, tmp + 1, j)    elif x == a[tmp]:        return "find it"print(binary_search(a, 45, 0, len(a) - 1))def binary_search1(L, x):    begin = 0    end = len(L) - 1    while begin < end:        temp = (begin + end) // 2        if x < L[temp]:            end = temp - 1        elif x > L[temp]:            begin = temp + 1        else:            return "find it"    return "don't find it"print(binary_search1(a, 45))