Python 算法之二分查找

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python 算法之二分查找相关的知识,希望对你有一定的参考价值。

 二分查找

二分查找又称折半查找

优点是比较次数少,查找速度快,平均性能好

缺点是要求待查表为有序表,且插入删除困难

折半查找方法适用于不经常变动而查找频繁的有序列表。  

 猜数字游戏

1、生成一个有序列表

2、用户猜测某个数字是否在列表中  

代码:

#!/usr/bin/env python
# -*- conding-utf8 -*-

def binary_search(data_source, find_n):
    mid = int(len(data_source)/2)
    if mid >= 1:
        if data_source[mid] > find_n: # data in left
            print("data in left of [%s]" % data_source[mid])
            print(data_source[:mid])
            binary_search(data_source[:mid], find_n)
        elif data_source[mid] < find_n: # data in right
            print("data in right of [%s]" % data_source[mid])
            print(data_source[mid:])
            binary_search(data_source[mid:], find_n)
        elif data_source[mid] == find_n:
            print("found %s" % data_source[mid])
    elif data_source[mid] == find_n:
        print("found %s" % data_source[mid])
    else:
        print("not found")


if __name__ == ‘__main__‘:
    data = list(range(1,100,3))
    ret = input("请输入猜测的数字:")
    binary_search(data, int(ret))  

运行结果:

请输入猜测的数字:50
data in right of [49]
[49, 52, 55, 58, 61, 64, 67, 70, 73, 76, 79, 82, 85, 88, 91, 94, 97]
data in left of [73]
[49, 52, 55, 58, 61, 64, 67, 70]
data in left of [61]
[49, 52, 55, 58]
data in left of [55]
[49, 52]
data in left of [52]
[49]
not found

请输入猜测的数字:1
data in left of [49]
[1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31, 34, 37, 40, 43, 46]
data in left of [25]
[1, 4, 7, 10, 13, 16, 19, 22]
data in left of [13]
[1, 4, 7, 10]
data in left of [7]
[1, 4]
data in left of [4]
[1]
found 1  

 

以上是关于Python 算法之二分查找的主要内容,如果未能解决你的问题,请参考以下文章

常见算法之二分查找

python s12 day4 算法基础之二分查找

python算法:二分查找

9.算法之顺序二分hash查找

44期盘点那些必问的数据结构算法题之二分查找算法

算法之二分查找PK线性查找