高性能二分查找算法Python精简版
在已有排序的列表中,如果需要高性能查找特定数,使用二分查找;即使是无序列表,也可以先采用O(nlogn)时间复杂度下排序,再二分查找也是不错的选择
def binary_search(li, left, right, num): while left < right: mid = (left + right) // 2 if li[mid] == num: return mid elif li[mid] > num: right = mid else: left = mid if __name__ == '__main__': data = [e for e in range(1000)] res = binary_search(data, 0, len(data), 23) print(res, data[res])
功能:第一个大于等于target的位置:
# the first >= n position def binary_search(nums, target): if not nums: return start, end = 0, len(nums)-1 while start + 1 < end: mid = start + (end-start) // 2 print(start, mid, end) if nums[mid] == target: end = mid elif nums[mid] > target: end = mid else: start = mid if nums[start] == target: return start if nums[end] == target: return end data = [1,2,4,4,4,6,9,22] print(binary_search(data, 4))
功能:第一个大于target的位置:
def binary_search(nums, target): if not nums: return start, end = 0, len(nums)-1 while start + 1 < end: mid = start + (end-start) // 2 print(start, mid, end) if nums[mid] == target: start = mid elif nums[mid] > target: end = mid else: start = mid if nums[start] == target: return start+1 if nums[end] == target: return end + 1 data = [1,2,4,4,4,6,9,22] print(binary_search(data, 4))
时刻记着自己要成为什么样的人!