Python数据结构——对有序表二分查找

list= [1, 5, 6, 9, 10, 51, 62, 65, 70]

查找5时:

 [1, 5, 6, 9, 10, 51, 62, 65, 70]        low=0    high=9    mid=(0+8)//2=4    list[mid]=list[4]=10

5<10:                                              low=0    high=3    mid=(0+3)//2=1   list[mid]=list[1]=5

5==5:                                              查找成功。返回下标mid=1

 

# -*- coding:utf-8 -*-
# file: pyBinarySearch.py
#
def BinarySearch(l, key):							# 二分查找
	low = 0
	high = len(l) - 1
	i = 0
	while (low <= high):
		i = i + 1
		mid = (high + low) // 2
		if (l[mid] < key):
			low = mid + 1
		elif (l[mid] > key):
			high = mid - 1
		else:
			print('use %d time(s)' % i)
			return mid
	return -1
if __name__ == '__main__':
	l = [1, 5, 6, 9, 10, 51, 62, 65, 70]			# 构造列表
	print(BinarySearch(l, 5))						# 在列表中查找
	print(BinarySearch(l, 10))
	print(BinarySearch(l, 65))
	print(BinarySearch(l, 70))

 

运行结果:

Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> 
 RESTART: G:\pyBinarySearch.py 
use 2 time(s)
1
use 1 time(s)
4
use 3 time(s)
7
use 4 time(s)
8

 

你可能感兴趣的:(Python,二分查找,python)