## 跟黄哥学python序列文章之python二分查找算法 原

黄哥Python培训

#跟黄哥学python序列文章之python二分查找算法

# 二分查找循环版

``````	#! /usr/bin/python
# coding:utf-8

def binary_search_while(key, arr):
'''list 必须是排序好的
黄哥python培训_python编程思路之四 咨询qq:1465376564
http://www.tudou.com/programs/view/Z4IClY5Wj-g/
运维如何通过学习python学会编程
https://github.com/pythonpeixun/article/blob/master/python/how_to_learn_python.md
黄哥python远程视频培训班
https://github.com/pythonpeixun/article/blob/master/index.md
黄哥python培训试看视频播放地址
https://github.com/pythonpeixun/article/blob/master/python_shiping.md
'''
start = 0
end = len(arr) - 1
while start <= end:
mid = start + (end - start) // 2
if arr[mid] < key:
start = mid + 1
elif arr[mid] > key:
end = mid - 1
else:
return mid
return -1

if __name__ == '__main__':
arr = [3, 9, 28, 67, 12, 45]
arr.sort()
print(binary_search_while(12, arr))
print(binary_search_while(3, arr))
print(binary_search_while(9, arr))
print(binary_search_while(99, arr))
``````

＃二分查找递归版

``````	#! /usr/bin/python
# coding:utf-8

def binary_search_recursion(key, arr, start, end):
'''list 必须是排序好的
黄哥python培训_python编程思路之四 咨询qq:1465376564
http://www.tudou.com/programs/view/Z4IClY5Wj-g/
运维如何通过学习python学会编程
https://github.com/pythonpeixun/article/blob/master/python/how_to_learn_python.md
黄哥python远程视频培训班
https://github.com/pythonpeixun/article/blob/master/index.md
黄哥python培训试看视频播放地址
https://github.com/pythonpeixun/article/blob/master/python_shiping.md
'''
if start > end:
return -1
mid = start + (end - start) // 2
if arr[mid] > key:
return binary_search_recursion(key, arr, start, mid - 1)
if arr[mid] < key:
return binary_search_recursion(key, arr, mid + 1, end)
return mid

if __name__ == '__main__':
arr = [3, 9, 28, 67, 12, 45]
arr.sort()
print(binary_search_recursion(12, arr, 0, len(arr)-1))
print(binary_search_recursion(3, arr, 0, len(arr)-1))
print(binary_search_recursion(9, arr, 0, len(arr)-1))
print(binary_search_recursion(99, arr, 0, len(arr)-1))
``````

#用途实例： 白名单过滤，有一家商业银行，将数千万客户名单保存为文本文件中，为白名单。

### 黄哥Python培训

dby_freedom
02/27
0
0
【python】手把手带你掌握算法基础01_二分法和选择排序法的实现

05/22
0
0
Python数据结构总结篇

2014/07/06
626
0
python实现lower_bound和upper_bound

mambakb
2018/11/29
0
0
python 二分插入、遍历目录

lvyz0207
2018/05/24
0
0

code-ortaerc

4
0

[TOC] 1.1.1标签操作v-text&v-html v-text：会把data中绑定的数据值原样输出。 v-html：会把data中值输出，且会自动解析html代码 <!--可以将指定的内容显示到标签体中--><标签 v-text=""></......

7
0
VMware vSphere的两种RDM磁盘

10
0
【AngularJS学习笔记】02 小杂烩及学习总结

14
0
Linux 内核的五大创新

18
0