首页 > 编程语言 > 详细

二分查找(python)

时间:2018-04-29 12:41:20      阅读:205      评论:0      收藏:0      [点我收藏+]

技术分享图片

 

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/4/29 9:11
# @Author  : Jackendoff
# @Site    : 
# @File    : 二分树.py
# @Software: PyCharm

data = [1,3,6,7,12,14,16,17,18,20,21,22,23,30,32,35]

def binary_serch(dataset,find_num):
    print(dataset)

    if len(dataset) > 1:
        mid = int (len(dataset)/2)
        if dataset[mid] == find_num:
            print(找到数字%s%find_num)
        elif dataset[mid] > find_num:
            print(找的数字在%s左边%dataset[mid])
            return binary_serch(dataset[0:mid],find_num)
        else:
            print("找的数字在%s右边"%dataset[mid])
            return  binary_serch(dataset[mid+1:],find_num)
    else:
        if dataset[0] == find_num:
            print(找到数字)
        else:
            print(没有这个数字)

binary_serch(data,35)



#结果如下

D:\untitled\venv\Scripts\python.exe D:/untitled/bogls/二分树.py
[1, 3, 6, 7, 12, 14, 16, 17, 18, 20, 21, 22, 23, 30, 32, 35]
找的数字在18右边
[20, 21, 22, 23, 30, 32, 35]
找的数字在23右边
[30, 32, 35]
找的数字在32右边
[35]
找到数字

Process finished with exit code 0

 

二分查找(python)

原文:https://www.cnblogs.com/serpent/p/8970561.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!