虚位以待(AD)
虚位以待(AD)
首页 > 脚本专栏 > python > python实现二分查找算法

python实现二分查找算法
类别:python   作者:码皇   来源:互联网   点击:

这篇文章主要为大家详细介绍了python实现二分查找算法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

二分查找算法:简单的说,就是将一个数组先排序好,比如按照从小到大的顺序排列好,当给定一个数据,比如target,查找target在数组中的位置时,可以先找到数组中间的数array[middle]和target进行比较,当它比target小时,那么target一定是在数组的右边,反之,则target在数组的左边,比如它比target小,则下次就可以只比较[middle+1, end]的数,继续使用二分法,将它一分为二,直到找到target这个数返回或者数组全部遍历完成(target不在数组中)

优点:效率高,时间复杂度为O(logN);
缺点:数据要是有序的,顺序存储。

python的代码实现如下:

    #!/usr/bin/python env# -*- coding:utf-8 -*-def half_search(array,target): low = 0 high = len(array) - 1 while low < high: mid = (low + high)/2 if array[mid] > target: high = mid - 1 elif array[mid] < target: low = mid + 1 elif array[mid] == target: print 'I find it! It is in the position of:',mid return mid else: print "please contact the coder!" return -1if __name__ == "__main__": array = [1, 2, 2, 4, 4, 5]

运行结果如下:

    I find it! It is in the position of: 44-1I find it! It is in the position of: 00-1

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

您可能感兴趣的文章:

  • python二分法实现实例
  • Python实现二分法算法实例
  • Python二分法搜索算法实例分析
  • Python编程实现二分法和牛顿迭代法求平方根代码
  • Python实现二维有序数组查找的方法
  • Python中的二叉树查找算法模块使用指南
  • python快速查找算法应用实例
  • Python实现二分查找算法实例
  • python二分查找算法的递归实现方法
  • 详解常用查找数据结构及算法(Python实现)
  • 简介二分查找算法与相关的Python实现示例
  • Python有序查找算法之二分法实例分析
相关热词搜索: python 二分查找