python实现二分查找算法

yipeiwu_com6年前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 -1



if __name__ == "__main__":
  array = [1, 2, 2, 4, 4, 5]

运行结果如下:

I find it! It is in the position of: 4
4
-1
I find it! It is in the position of: 0
0
-1

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

PyTorch实现ResNet50、ResNet101和ResNet152示例

PyTorch实现ResNet50、ResNet101和ResNet152示例

PyTorch: https://github.com/shanglianlm0525/PyTorch-Networks import torch import torch.nn...

Python利用QQ邮箱发送邮件的实现方法(分享)

废话不多说,直接上代码 Python2.7 #!/usr/bin/env python2.7 # -*- coding=utf-8 -*- import smtplib from...

深入解析Python编程中JSON模块的使用

JSON编码支持的基本数据类型为 None , bool , int , float 和 str , 以及包含这些类型数据的lists,tuples和dictionaries。 对于di...

使用apiDoc实现python接口文档编写

apiDoc的安装 npm install apidoc -g 点击官方文档 生成api的终端命令:apidoc -i 代码所在路径-o 生成文件的路径 接口文档的编写 文件的简介...

详解python中各种文件打开模式

在python中,总的来说有三种大的模式打开文件,分别是:a, w, r 当以a模式打开时,只能写文件,而且是在文件末尾添加内容。 当以a+模式打开时,可以写文件,也可读文件,可是在读文...