python 快排,堆排,归并

本文详细介绍了归并排序、快速排序及堆排序三种经典的排序算法。包括每种算法的具体实现过程,如归并排序通过递归将数组分成更小的部分再合并;快速排序选择随机基准值进行分区排序;堆排序则通过构建最大堆实现排序。文章提供了完整的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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值