二分查找(python)

#!/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

猜你喜欢

转载自www.cnblogs.com/serpent/p/8970561.html