在Python中可以利用bisect模块来实现二分搜索,该模块包含函数只有几个:

Python学习笔记:bisect模块实现二分搜索-LMLPHP

import bisect

L = [1,3,4,5,5,5,8,10]
x = 5 bisect.bisect_left(L,x) #
# 在L中查找x,x存在时返回x最左侧的位置,x不存在返回应该插入的位置 bisect.bisect_right(L,x) #
# 在L中查找x,x存在时返回x最右侧的位置,x不存在返回应该插入的位置 bisect.insort_left(L,x) # [1, 3, 4, 5, 5, 5, 5, 8, 10]
# 将x插入到列表L中,x存在时插入在左侧 bisect.insort_right(L,x) # [1, 3, 4, 5, 5, 5, 5, 5, 8, 10]
# 将x插入到列表L中,x存在时插入在右侧

  bisect.insort_leftbisect.insort_right貌似没什么差别,作用基本一致。

  另外,bisect.bisect(L,x)与bisect_right相同,insort与insort_right相同。

  例子:

import bisect
import random mylist = list()
for i in range(10):
num = random.randint(1,100)
index = bisect.bisect_left(mylist, num)
bisect.insort_left(mylist, num)
print('num ', str(num), 'index ', str(index), 'list ', mylist) mylist = list()
for i in range(10):
num = random.randint(1,100)
index = bisect.bisect_right(mylist, num)
bisect.insort_right(mylist, num)
print('num ', str(num), '\tindex ', str(index), '\tlist ' ,mylist)

  输出:

num  72 index  0 list  [72]
num 89 index 1 list [72, 89]
num 41 index 0 list [41, 72, 89]
num 45 index 1 list [41, 45, 72, 89]
num 100 index 4 list [41, 45, 72, 89, 100]
num 1 index 0 list [1, 41, 45, 72, 89, 100]
num 69 index 3 list [1, 41, 45, 69, 72, 89, 100]
num 4 index 1 list [1, 4, 41, 45, 69, 72, 89, 100]
num 76 index 6 list [1, 4, 41, 45, 69, 72, 76, 89, 100]
num 11 index 2 list [1, 4, 11, 41, 45, 69, 72, 76, 89, 100] num 82 index 0 list [82]
num 39 index 0 list [39, 82]
num 27 index 0 list [27, 39, 82]
num 78 index 2 list [27, 39, 78, 82]
num 9 index 0 list [9, 27, 39, 78, 82]
num 80 index 4 list [9, 27, 39, 78, 80, 82]
num 58 index 3 list [9, 27, 39, 58, 78, 80, 82]
num 42 index 3 list [9, 27, 39, 42, 58, 78, 80, 82]
num 59 index 5 list [9, 27, 39, 42, 58, 59, 78, 80, 82]
num 50 index 4 list [9, 27, 39, 42, 50, 58, 59, 78, 80, 82]

END 2018-11-01 23:25:37

04-26 16:34