zoukankan      html  css  js  c++  java
  • 快速排序(python实现)

    算法导论上的快速排序采用分治算法,步骤如下:

    1.选取一个数字作为基准,可选取末位数字

    2.将数列第一位开始,依次与此数字比较,如果小于此数,将小数交换到左边,最后达到小于基准数的在左边,大于基准数的在右边,分为两个数组

    3.分别对两个数组重复上述步骤

    其中一次排序步骤如下:

    伪码实现:

    QuickSort(A,p,r)
        if p<r
            then q = Partition(A,p,r)
                QucikSort(A,p,q-1)
                QucikSort(A,q+1,r)
    
    Partition(A,p,r)
        x=A[r]
        i=p-1
        for j from p to r-1
            if A[j]<=x
                then i=i+1
                    exchange A[i],A[j]
        exchange A[i+1],A[r]
        return i+1
    

      

    Python实现代码如下:

    def QuickSort(arr,firstIndex,lastIndex):
        if firstIndex<lastIndex:
            divIndex=Partition(arr,firstIndex,lastIndex)
    
            QuickSort(arr,firstIndex,divIndex)        
            QuickSort(arr,divIndex+1,lastIndex)
        else:
            return
    
    
    def Partition(arr,firstIndex,lastIndex):
        i=firstIndex-1
        for j in range(firstIndex,lastIndex):
            if arr[j]<=arr[lastIndex]:
                i=i+1
                arr[i],arr[j]=arr[j],arr[i]
        arr[i+1],arr[lastIndex]=arr[lastIndex],arr[i+1]
        return i
    
    
    arr=[1,4,7,1,5,5,3,85,34,75,23,75,2,0]
    
    print("initial array:
    ",arr)
    QuickSort(arr,0,len(arr)-1)
    print("result array:
    ",arr)
    

      运行结果如下:

    initial array:
    [1, 4, 7, 1, 5, 5, 3, 85, 34, 75, 23, 75, 2, 0]
    result array:
    [0, 1, 1, 2, 3, 4, 5, 5, 7, 23, 34, 75, 75, 85]

    性能分析以后做

  • 相关阅读:
    ●BZOJ 2752 [HAOI2012]高速公路(road)
    ●UVA 11021 tunnello
    ●POJ 2794 Double Patience
    【51Nod1555】布丁怪
    【LG1600】[NOIP2016]天天爱跑步
    【LG5171】Earthquake
    【LG4437】[HNOI/AHOI2018]排列
    【CF1097F】Alex and a TV Show
    【51Nod 1769】Clarke and math2
    【LG5330】[SNOI2019]数论
  • 原文地址:https://www.cnblogs.com/feichangnice/p/5334195.html
Copyright © 2011-2022 走看看