python 练习之二分查找

#!/usr/bin/env python3

# -*- coding: utf-8 -*-

data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 18, 20, 23, 26, 30]

def binary_search(find_str, data_set, count):
    mid = int(len(data_set)/2)
    if mid == 0:
        if data_set[mid] == find_str:
            print("find it", find_str, data.index(find_str))   ###data.index 求查找的数在原list中的下标
        else:
            print("canot find it", count)
        return
    if data_set[mid] == find_str:   #如果等于则找到,返回
        print("find it", find_str, mid)
    elif data_set[mid] > find_str:   #如果大于则在左边找
        print("find in left", data_set[mid], data_set[0:mid])
        binary_search(find_str, data_set[0:mid], count+1)
    else:   #如果小于则在右边寻找
        print("find in right", data_set[mid], data_set[mid+1:])
        binary_search(find_str, data_set[mid+1:], count+1)


binary_search(11, data, 0)

 

posted on 2018-03-06 09:09  李永山  阅读(94)  评论(0编辑  收藏  举报

导航