python sort

快速排序

 //理解参考go的快速排序

def sort(listv,left,right):
    #print listv
    i,j=left,right
    temp=listv[left]
    p=left
    while i<=j:
        #print j,p
        while j>=p and listv[j]>=temp :
            j-=1
        if j>=p:
            listv[p]=listv[j]
            p=j
        if listv[i]<=temp and i<=p:
            i+=1
        if i<=p:
            listv[p]=listv[i]
            p=i
    listv[p]=temp
    if p-left >1:
        sort(listv,left,p-1)
    if right-p>1:
        sort(listv,p+1,right)
    #重要
    return listv   




z=[20, 21, 1, 3, 4, 25, 7, 8, 26, 27]
lenv=len(z)
print sort(z,0,lenv-1)

result

huzh@DESKTOP-LFIDO1U ~/code/python/python2
$ python quc.py
[1, 3, 4, 7, 8, 20, 21, 25, 26, 27]

选择排序

def sort(lst):
    if len(lst)<2:
        print "lst <2"
        return
    for i in range (1,len(lst)):
        print "iiiiii",i
        j=i
        temp=lst[i]
        #temp不能用lst[i]
        while lst[j-1]>temp :
            lst[j]=lst[j-1]
            #防止访问越界
            if j>0:
                j-=1
            else:
                #增加跳出条件
                break
        lst[j]=temp

    print  lst


z=[20,21,2,3,25,7,8,41,42]
sort(z)
View Code

huzh@DESKTOP-LFIDO1U ~/code/python/python2
$ python insert.py
[2, 3, 7, 8, 20, 21, 25, 41, 42]

 

posted @ 2019-01-23 14:22  voh99800  阅读(175)  评论(0编辑  收藏  举报