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]

    性能分析以后做

  • 相关阅读:
    Go语言中DateTime知识点
    Go语言中的string知识点
    Go语言中的Iota
    Go语言的通道(2)-缓冲通道
    Go语言的通道(1)-无缓冲通道
    Go语言协程
    设计一个好的通用组件
    Windows服务器【由于系统缓冲区空间不足或队列已满,不能执行套接字上的操作】问题调查
    Go语言的并发
    SCSS 中的 &::before 和 &::after
  • 原文地址:https://www.cnblogs.com/feichangnice/p/5334195.html
Copyright © 2011-2022 走看看