二分法

博客围绕在有序序列中查找数字展开,介绍了递归和循环两种查找方式。递归是函数自身调用自身,有明确退出条件,但多次调用耗内存;还提及不能排序直接用二分法求最大值索引值的情况。

要求在一个有序序列中,例如[0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99],查找一个数字,如果找到则打印该数字,如果找不到,则输出“not found!”

 

1:递归方式

递归,是在函数中自身调用自身的一种情况,直到有一个明确的退出条件成立后结束相互调用。递归是一种很容易理解某类问题的方式,但是不是特别高效,因为每次调用自身时,都会在内存中创建一个新的内存空间,当不断循环调用非常多次时,是非常耗内存的。

#!/usr/bin/env python 
# -*- coding: utf-8 -*-


def recursion_search(data_source, find_n):
    mid = len(data_source) / 2
    if len(data_source) >= 1:
        if find_n > data_source[mid]:
            recursion_search(data_source[mid + 1:], find_n)
        elif find_n < data_source[mid]:
            recursion_search(data_source[:mid], find_n)
        else:
            print data_source[mid]
    else:
        print "not found !"


if __name__ == '__main__':
    test_array = range(0, 100, 3)
    recursion_search(test_array, 99)

2:循环方式

#!/usr/bin/env python 
# -*- coding: utf-8 -*-


def loop_search(data_source, find_n):
    while len(data_source):
        mid = len(data_source) / 2
        if find_n < data_source[mid]:
            data_source = data_source[:mid]
        elif find_n > data_source[mid]:
            data_source = data_source[mid + 1:]
        else:
            print data_source[mid]
            break
    else:
        print "not found !"


if __name__ == '__main__':
    test_array = range(0, 100, 3)
    loop_search(test_array, 99)

 

 

2、不能排序直接用二分法求出来最大值的索引值[1,2,4,6,3,1] 

list = [1,2,4,6,3,1]
def twosplit(list,left,right):
    while (left<=right):
        mid  = (left+right)//2
        if list[mid]>list[mid - 1] and list[mid]>list[mid + 1]:
            return mid
        elif list[mid]>list[mid-1] and list[mid]<list[mid + 1]:
            left = mid
        else:
            right = mid

if __name__ =="__main__":
    print(twosplit(list, 0, len(list) - 1))

 

# 给定一个排好序(升序)的列表与待查找的关键字,成功则返回其索引,失败则返回-1。
def search(list, key):
    left = 0     # 左边界
    right = len(list) - 1   # 右边界
    while left <= right:
        mid = (left + right) // 2  # 取得中间索引
        if key > list[mid]:
            left = mid + 1
        elif key < list[mid]:
            right = mid - 1
        else:
            return mid
    else:
        return -1

list = [2, 5, 13, 21, 26, 33, 37]
print(search(list, 21))

 

转载于:https://www.cnblogs.com/lmh001/p/10566980.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值