python实现:使用二分查找,查找有序数组中,一个数字最后出现的下标
问题:
使用二分查找,查找有序数组[2,2,3,3,3,4,5,5,6,6,7,8,8]中,数字3最后出现的下标。
解析:
二分查找:先获取数组的中间值与参数对比,判断两者的值,截取符合条件的一半数据为新的数组,重新判断……
代码:
#coding:utf8 def binary_search(list,item): if not list and not item: print "he" return None low = 0 high = len(list)-1 while low <= high: mid = (low + high)/2 print "low %d" % low print "high %d" % high print "mid %d" % mid guess = list[mid] print "guess %s" % guess if guess == item: return seach(list,item,mid) elif guess > item: high = mid - 1 elif guess < item: low = mid + 1 def seach(list,item,mid): for k,v in enumerate(list[mid:]): if v == item: continue else: return k+mid int1 = [2,2,3,3,3,4,5,5,6,6,7,8,8] intItem = 3 a = binary_search(int1,intItem)
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。