Python实现二分查找
2015-04-03 11:08
489 查看
http://blog.csdn.net/vipygd/article/details/7555759
这么晚,没事干,写个程序练练手,最近在看Python,就拿Python开刀吧;上oschina看有人写了个二分查找的东西,看了下有问题,所以自己忍不住也拿出来写写;纯练手!!!
[python] view
plaincopyprint?
'fileName--BinarySearch.py'
src = []
def BinarySearch(low, high, target, *src):
'二分查找'
while low <= high:
mid = (low + high) // 2
midVal = src[mid]
if target < midVal:
high = mid - 1
elif target > midVal:
low = mid + 1
else:
return mid
BinarySearch(low, high, target, *src)
print('Please input 10 number:')
for number in range(10):
src.append(int(input('Num %d:' % number)))
sortList = tuple(src)
key = int(input('Please input key:'))
location = BinarySearch(0, len(src) - 1, key, *sortList)
if location != None:
print('Find target at %d' % (location + 1))
else:
print('No target!')
这么晚,没事干,写个程序练练手,最近在看Python,就拿Python开刀吧;上oschina看有人写了个二分查找的东西,看了下有问题,所以自己忍不住也拿出来写写;纯练手!!!
[python] view
plaincopyprint?
'fileName--BinarySearch.py'
src = []
def BinarySearch(low, high, target, *src):
'二分查找'
while low <= high:
mid = (low + high) // 2
midVal = src[mid]
if target < midVal:
high = mid - 1
elif target > midVal:
low = mid + 1
else:
return mid
BinarySearch(low, high, target, *src)
print('Please input 10 number:')
for number in range(10):
src.append(int(input('Num %d:' % number)))
sortList = tuple(src)
key = int(input('Please input key:'))
location = BinarySearch(0, len(src) - 1, key, *sortList)
if location != None:
print('Find target at %d' % (location + 1))
else:
print('No target!')
相关文章推荐
- Python 实现查找的几种类型 (线性查找,线性有序查找,线性查找最小值,二分查找)
- python实现二分查找
- 排序和搜索(二)——python实现二分查找
- 二分查找算法之python实现
- 二分查找算法python实现
- [Python]二分查找算法实现
- python实现二分查找
- python实现的二分查找
- 二分查找算法及python实现
- Python实现二分查找与bisect模块详解
- 算法基础之python实现贪心算法中圣诞老人分糖果问题和二分查找算法中烘干衣服问题
- 用Python实现二分查找
- c++/java/python 实现二分查找
- 二分查找的两种实现方式(递归和非递归)--python实现
- python实现二分查找
- 算法-二分查找-python实现
- 二分查找算法Python3实现
- 凤凰网招聘二分查找python实现
- 二分查找 python实现
- python中实现二分查找,插入排序,归并排序,快速排序