二分法排序-Python实现

有一个无序序列[37,99,73,48,47,40,40,25,99,51],先进行排序打印输出,分别尝试插入20/40/41 数值到序列中合适的位置,保证其有序。

1、for 循环实现

第一种实现,利用嵌套for循环,每次迭代出来的数值进行比较。如果比原表中的数值小,则插入到这个数左面。

 

 

 

lst1 = [37,99,73,48,47,40,40,25,99,51]
lst = sorted(lst1)

for x in (20,40,41,100):
    i = 0
    for i,v in enumerate(lst):
        if v > x:
            break
    lst.insert(i,x)
print(lst)

2、利用二分法实现

排序后二分查找到适当位置插入数值。

排序使用sorted解决,假设升序输出。

查找插入点,使用二分查找完成。

假设全长为n,首先在大致的中点元素开始和待插入的数进行比较,如果大则和右边的区域的中点元素进行比较,如果小则和左边的区域的中点进行比较,以此类推。

 

 

lst = [37, 99, 73, 48, 47, 40, 40, 25, 99, 51]
lst1 = sorted(lst)
def lst_insert(lst1,i):
    ret = lst1
    # print(ret)
    length = len(lst1)
    low = 0
    while low < length:
        mid = length // 2
        if ret[mid] < i:
            low = mid + 1       #说明i大,右边,限制下限。
        else:
            length = mid      #说明i不大于,左边,限制上限。
    ret.insert(low,i)
    print(ret)
for x in (40,20,21):
    lst_insert(lst1,x)

 

 

算法的核心就是折半至重合为止。

 

 

3、二分

1)二分的前提是有序,否则不允许。

2)二分的查找算法的时间复杂度是O(log n)

4、Bisect模块

提供的函数有:

bisect.bisect_left(a,x,lo=0,hi=len(a)):

查找在有序列表a中插入x的index。Lo和hi用于指定列表的区间,默认是使用整个列表,如果x已经存在,在其左边插入,返回值为index。

 

bisect.bisect_right(a,x,lo= 0,hi=len(a))或者bisect.bisect(a,x,lo= 0,hi=len(a))

和bisect_left类似,但如果x已经存在,则在其右边插入。

 

bisect.insort_left(a,x,lo= 0,hi=len(a))

在有序列表a中插入x,等同于a.insert(bisect.bisect_left(a,x,lo,hi),x).

 

bisect.insort_right(a,x,lo= 0,hi=len(a))或者bisect.insort(a,x,lo= 0,hi=len(a))和insort_left函数类似,但是如果x如果已经存在,在其右边插入。

 

 

函数可以分为两类:

Bisect系,用于查找index。

Insort系,用于实际插入。

默认重复时候从右边插入。

 

import bisect


lst = [37, 99, 73, 48, 47, 40, 40, 25, 99, 51]
lst1 = sorted(lst)
print(lst1)  #[25, 37, 40, 40, 47, 48, 51, 73, 99, 99]
print(20,bisect.bisect(lst1,20))    #20 0
print(30,bisect.bisect(lst1,30))    #30 1
print(40,bisect.bisect(lst1,40))    # 40 4
print(100,bisect.bisect(lst1,100))    #  100 10

print(20,bisect.bisect_left(lst1,20))   #20 0
print(30,bisect.bisect_left(lst1,30))   #30 1
print(40,bisect.bisect_left(lst1,40))   #40 2
print(100,bisect.bisect_left(lst1,100))   # 100 10

for x in (20,30,40,100):
    bisect.insort_left(lst1,x)
    print(lst1)
    # [20, 25, 37, 40, 40, 47, 48, 51, 73, 99, 99]
    # [20, 25, 30, 37, 40, 40, 47, 48, 51, 73, 99, 99]
    # [20, 25, 30, 37, 40, 40, 40, 47, 48, 51, 73, 99, 99]
    # [20, 25, 30, 37, 40, 40, 40, 47, 48, 51, 73, 99, 99, 100]

 

5、二分应用

判断学习成绩,成绩等级A-E  。90分以上为A ,80 以上为B  ,70以上为C  60以上为D。60以下为D。

 


def insert_score(nums):
    lst = [60, 70, 80, 90]
    grades = "EDCBA"
    index = bisect.bisect(lst,nums)
    print(index)
    print(grades[index])
insert_score(70)
posted @ 2018-11-12 16:23  Python爱好者666  阅读(3331)  评论(0编辑  收藏  举报