python二分查找算法的递归实现方法

yipeiwu_com6年前Python基础

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

这里先提供一段二分查找的代码:

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

近来喜欢递归的简单明了,所以修改成递归的方法:

def binSearch(lst, item):
  mid = len(lst) //2
  found = False
  if lst[mid] ==
item:
 found = True
 return found
  if mid == 0:
#mid等于0就是找到最后一个元素了。
 found = False
 return found
  else:
 if item > lst[mid]: #找后半部分
   #print(lst[mid:])
   return
binSearch(lst[mid:], item)
 else:
   return
binSearch(lst[:mid], item) #找前半部分

测试通过。

更多关于Python相关内容可查看本站专题:《Python正则表达式用法总结》、《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

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

相关文章

浅谈Python脚本开头及导包注释自动添加方法

浅谈Python脚本开头及导包注释自动添加方法

1、开头:#!/usr/bin/python和# -*- coding: utf-8 -*-的作用 – 指定 #!/usr/bin/python 是用来说明脚本语言是python的 是要...

Python FTP两个文件夹间的同步实例代码

具体代码如下所示: # -*- coding: utf-8 -*- ''''''' ftp自动检测源文件夹的更新,将源文件夹更新的内容拷贝到目标文件夹中 使用树的层序遍...

python中星号变量的几种特殊用法

一、什么是星号变量 最初,星号变量是用在函数的参数传递上的,在下面的实例中,单个星号代表这个位置接收任意多个非关键字参数,在函数的*b位置上将其转化成元组,而双星号代表这个位置接收任意...

解决Ubuntu pip 安装 mysql-python包出错的问题

问题描述如下,报没有找到mysql_config环境变量 $ pip install mysql-python Collecting MySQL-python==1.2.5 (f...

理想高通滤波实现Python opencv示例

理想高通滤波实现Python opencv示例

理想高通滤波实现 python opencv import numpy as np import cv2 from matplotlib import pyplot as plt...