python 快排,堆排,归并

#归并排序
def mergeSort(a,L,R) :
    if(L>=R) :
        return
    mid=((L+R)>>1)
    mergeSort(a,L,mid)
    mergeSort(a,mid+1,R)
    p=L
    q=mid+1
    t=[]
    while(p<=mid and q<=R) :
        if a[p]<=a[q] :
            t.append(a[p])
            p+=1
        if a[p]>a[q] :
            t.append(a[q])
            q+=1
    while (p<=mid) :
        t.append(a[p])
        p+=1
    while(q<=R) :
        t.append(a[q])
        q+=1
    cur=0
    for i in range(L,R+1) :
        a[i]=t[cur]
        cur+=1

a=[2,3,5,1,5]
mergeSort(a,0,4)
print a

#快速排序
import random

def Qsort(a) :
    if a==[] :
        return []
    val=random.choice(a)
    return Qsort([x for x in a if x<val]) + [x for x in a if x==val] +Qsort([x for x in a if x>val])

a=[1,3,4,6,2,4]
a=Qsort(a)

#堆排
def heapAjust(a,pos,sz) :
    if(pos>sz/2) :
        return
    Lchild=pos*2
    Rchild=pos*2+1
    Max=pos
    if(Lchild<=sz and a[Lchild]>a[Max]) :
        Max=Lchild
    if(Rchild<=sz and a[Rchild]>a[Max]) :
        Max=Rchild
    if(Max!=pos) :
        a[Max],a[pos]=a[pos],a[Max]
        heapAjust(a,Max,sz)
    
def buildHeap(a,sz) :
    for i in range(sz/2,0,-1) :
        heapAjust(a,i,sz)
def heapSort(a,sz) :
    buildHeap(a,sz)
    for i in range(sz,0,-1) :
        a[i],a[1]=a[1],a[i]
        heapAjust(a,1,i-1)

a=[0,1,2,5,3,4,6]
heapSort(a,6)
print a
原文地址:https://www.cnblogs.com/acvc/p/4660923.html