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
  • 相关阅读:
    ASP.NET 点击前台服务器按钮后, 刷新. 重新执行 按钮事件
    动态绑定数据日历jquery
    前端及移动端学习 笔记 -待更新
    jq 兼容性 ie7,ie8
    jQuery中的$(window).load()与$(document).ready()
    SqlServer中循环和条件语句示例!
    调用一般处理程序 提供接口api
    background-position: -24px 0px
    中奖名单滚动
    在此上下文中不允许使用子查询
  • 原文地址:https://www.cnblogs.com/acvc/p/4660923.html
Copyright © 2011-2022 走看看