二分查找的递归与非递归方式

遇到二分查找没有思路吗,请查看。

'''

# 非递归方式二分法查找

def binsearch(list2,num):
    paixu(list2)# 进行二分查找一定是对于有序数组
    print(list2)
    leng = len(list2)# 求计算的列表长度
    start = 0
    end = leng-1
    while start <= end:
        mid = (start+end) // 2
        print('mid%d'%mid)
        if num < list2[mid]:
            end = mid-1
        elif num > list2[mid]:
            start = mid+1
        else:
            return mid
    return -1


def paixu(list1):
    leng = len(list1)
    for i in range(leng):
        for j in range(i, leng - i - 1):
            if list1[j] > list1[j + 1]:
                list1[j], list1[j + 1] = list1[j + 1], list1[j]
    return list1

list1 = [12,34,65,23,54,65,78,25,90]
print(binsearch(list1,54))#排序后的索引

'''

# 递归解决二分法查找
def paixu(list1):
    leng = len(list1)
    for i in range(leng):
        for j in range(i, leng - i - 1):
            if list1[j] > list1[j + 1]:
                list1[j], list1[j + 1] = list1[j + 1], list1[j]
    return list1

def bin_search(list1,left,right,num):
    paixu(list1)
    if left > right:
        return -1
    mid = (right+left) // 2
    print('mid=%d'%mid)
    if list1[mid] == num:
        return mid
    elif list1[mid] > num:
        bin_search(list1,left,right-mid,num)
    else:
        bin_search(list,left-mid,right,num)


list1 = [12,34,65,23,54,65,78,25,90]
leng = len(list1)
print(bin_search(list1,0,leng-1,54))#排序后的索引

 

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页