python二分法查找算法实现方法【递归与非递归】

yipeiwu_com5年前Python基础

本文实例讲述了python二分法查找算法实现方法。分享给大家供大家参考,具体如下:

二分法查找

二分查找又称折半查找,优点是比较次数少,查找速度快,平均性能好;其缺点是要求待查表为有序表,且插入删除困难。因此,折半查找方法适用于不经常变动而查找频繁的有序列表。首先,假设表中元素是按升序排列,将表中间位置记录的关键字与查找关键字比较,如果两者相等,则查找成功;否则利用中间位置记录将表分成前、后两个子表,如果中间位置记录的关键字大于查找关键字,则进一步查找前一子表,否则进一步查找后一子表。重复以上过程,直到找到满足条件的记录,使查找成功,或直到子表不存在为止,此时查找不成功。

二分法查找实现

(非递归实现)

def binary_search(alist, item):
  first = 0
  last = len(alist)-1
  while first<=last:
    midpoint = (first + last)/2
    if alist[midpoint] == item:
      return True
    elif item < alist[midpoint]:
      last = midpoint-1
    else:
      first = midpoint+1
  return False
testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42,]
print(binary_search(testlist, 3))
print(binary_search(testlist, 13))

(递归实现)

def binary_search(alist, item):
  if len(alist) == 0:
    return False
  else:
    midpoint = len(alist)//2
    if alist[midpoint]==item:
      return True
    else:
      if item<alist[midpoint]:
        return binary_search(alist[:midpoint],item)
      else:
        return binary_search(alist[midpoint+1:],item)
testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42,]
print(binary_search(testlist, 3))
print(binary_search(testlist, 13))

运行结果:

False
True

时间复杂度

  • 最优时间复杂度:O(1)
  • 最坏时间复杂度:O(logn)

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数据结构与算法教程》、《Python列表(list)操作技巧总结》、《Python编码操作技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

希望本文所述对大家Python程序设计有所帮助。

相关文章

python操作小程序云数据库实现简单的增删改查功能

python操作小程序云数据库实现简单的增删改查功能

不止python,你可以利用任何语言那实现通过http请求来操作你自己的小程序云数据库了 背景 也是在最近吧,小程序更新了云开发 HTTP API 文档,提供了小程序外访问云开发资源的能...

python 实现堆排序算法代码

复制代码 代码如下: #!/usr/bin/python import sys def left_child(node): return node * 2 + 1 def right_c...

python统计文本文件内单词数量的方法

本文实例讲述了python统计文本文件内单词数量的方法。分享给大家供大家参考。具体实现方法如下: # count lines, sentences, and words of a t...

Python实现的各种常见分布算法示例

Python实现的各种常见分布算法示例

本文实例讲述了Python实现的各种常见分布算法。分享给大家供大家参考,具体如下: #-*- encoding:utf-8 -*- import numpy as np from s...

python 字符串和整数的转换方法

数字转成字符串 方法一: 使用格式化字符串: tt=322 tem='%d' %tt tem即为tt转换成的字符串 常用的格式化字符串: %d 整数 %f%F 浮点数 %e%E...