您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

Python二分查找详解

2024/3/30 18:09:10发布13次查看
先来看个实例
#!/usr/bin/env python import sys def search2(a,m): low = 0 high = len(a) - 1 while(low =start: mid = (start+end)//2 print(mid) if nums[mid]>target: end = mid-1 elif nums[mid]=start and nums[mid+value] == target: end = mid+value else: return mid else: if mid+1<=end and nums[mid+value] == target: start = mid+value else: return mid return -1 a=binary_search(0,len(nums)-1,-1) b=binary_search(0,len(nums)-1,1) return [a,b]a = solution()l = [2,2]print(a.searchrange(l,2))
二分算法的定义不在多说了,百度一下就知道(支持国产大笑)
import sys source = [1,2,3,4,5,6,7,8,9,10] #must be in order des = int(sys.argv[1]) low = 0 high = len(source) - 1 targetindex = -1 print des=,des while low <= high: middle = (low + high)/2 if des == source[middle]: targetindex = middle break elif des < source[middle]: high = middle -1 print middle element[index=,middle,,value=,source[middle],] is bigger than des, continue search from[,low,to,high,] else: low = middle + 1 print middle element[index=,middle,,value=,source[middle],] is smaller than des, continue search from[,low,to,high,] print search complete, target element's index in source list is ,targetindex
最后在分享一个
'filename--binarysearch.py' src = [] def binarysearch(low, high, target, *src): '二分查找' while low <= high: mid = (low + high) // 2 midval = src[mid] if 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!')
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product