码迷,mamicode.com
首页 > 编程语言 > 详细

Python 算法之二分查找

时间:2017-10-18 12:32:35      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:arc   频繁   有序列表   sea   二分查找   ==   highlight   binary   速度   

 二分查找

二分查找又称折半查找

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

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

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

 猜数字游戏

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 算法之二分查找

标签:arc   频繁   有序列表   sea   二分查找   ==   highlight   binary   速度   

原文地址:http://www.cnblogs.com/python-gm/p/7685870.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!