首页 > 其他分享 >递归、二分查找

递归、二分查找

时间:2022-09-05 20:56:16浏览次数:67  
标签:二分 index end 递归 binary start 查找 numb return

#递归函数: 有最大递归深度,默认接近1000,各版本略有差异
count = 0
def F1(n):
    n += 1
    print(n)#1  2   3……996
    F1(n)

F1(count)

#修改递归深度
import sys

sys.setrecursionlimit(100)

count = 0

def F2(n):
    n += 1
    print(n)  # 1  2   3……96
    F2(n)

F2(count)


#二分查找:必须是无重复数字的有序序列
def binary_search(L, numb, start = 0, end = None):
    if end is None:
        end = len(L) - 1
    m_index = (end - start) // 2 + start
    if start < end:
        if numb < L[m_index]:
            return binary_search(L, numb, start = start, end = m_index)
        elif numb > L[m_index]:
            return binary_search(L, numb, start = m_index, end = end)
        elif numb == L[m_index]:
            return m_index
        else:
            return None
    else:
        return None


L1 = [1, 3, 5, 6, 7, 8, 11, 23, 44, 46, 53]
print(binary_search(L1, 7))#4


#

 

标签:二分,index,end,递归,binary,start,查找,numb,return
From: https://www.cnblogs.com/ggsdddup/p/16659543.html

相关文章