zoukankan      html  css  js  c++  java
  • 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)
  • 相关阅读:
    sql server 去掉重复项
    mvc2.0与3.0 便利一行三个元素 便利多行代码
    新距离
    Android
    Java
    计算机文化基础期末考试复习
    立体的导航条
    腾讯微博
    1637
    私有变量
  • 原文地址:https://www.cnblogs.com/liyongshan/p/8512399.html
Copyright © 2011-2022 走看看