• 技术文章 >Python技术 >Python基础教程

    python二分查找的原理分析

    小妮浅浅小妮浅浅2021-10-23 10:01:33原创3658

    1、将中间标值mid的元素e取到数列中,进行查找元素key的比较。

    2、如果相等查找成功,若不等,大于则只需在后半部分查找,小于则需在前半部分查找。

    实例

    def binary_search(my_list, key):
        left = 0
        right = len(my_list)
        while left <= right:
            mid = (right - left) // 2
            if my_list[left + mid] < key:
                left = left + mid + 1
            elif my_list[left + mid] > key:
                right = left + mid - 1
            else:
                return left + mid
        return "None"
     
     
    if __name__ == "__main__":
        my_list = [1, 3, 5, 7, 9, 11, 13]
        print("二分查找的原始数列:", my_list)
        print("二分查找的返回结果:", binary_search(my_list, 3))

    以上就是python二分查找的原理,希望对大家有所帮助。更多Python学习指路:python基础教程

    本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

    专题推荐:python 二分查找
    品易云
    上一篇:python中camel函数的使用 下一篇:python字符串中变量的使用

    相关文章推荐

    • python函数实参的四种类型• python变量名的查找方法• python格式化经纬度的方法• python多进程如何优化显示进度条• python多进程中多个参数函数的使用• python中format_map的使用• python zip_longest和zip的比较• python __dict__的使用注意• python有哪些字符串查找类方法• python字符串分隔类方法的总结• python中camel函数的使用

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网