zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    第3章 HBase完全分布式集群搭建
    第2章 大数据处理架构Hadoop(二)
    第2章 大数据处理架构Hadoop (一)
    SQL 优化
    EXCEL快捷键 输入第一格的公式,计算这列剩下的单元格
    IDEA快捷键,IDEA2021激活码
    IDEA激活码高质量的,IDEA2021一次破解激活永久版
    shardingsphere 分库分表解决方案
    网络编程(笔记四)
    网络编程(笔记三)
  • 原文地址:https://www.cnblogs.com/acvc/p/4660923.html
Copyright © 2011-2022 走看看