zoukankan      html  css  js  c++  java
  • 【算法导论】第7章,快速排序

    快排的优势:

    1、期望为O(n lgn)

    2、常数因子比较小

    3、就地排序

    4、在虚存环境很好工作

    与合并排序一样是分治思想,但是不是从中间截断,而是通过partition过程代替取中位数的操作。

    partition过程:下标p到r

    每次选择最后一个元素为x,然后小的放前面,大的放后面,用ij两个坐标实现:

    i=p-1, j循环过去,如果j位置上小于x, i++ ij数值互换。最终换i+1和r的元素。

    代码:

    def quickSort(xlist, start=0, end=None):
        if end is None:
            end = len(xlist) - 1
    
        if start >= end:
            pass
    
        if start < end:
            position = frac(xlist, start, end)
            quickSort(xlist, start, position - 1)
            quickSort(xlist, position + 1, end)
    
        return xlist
    
    
    def frac(xList, start, end):
        value = xList[start]
        valuePosition = start
        small = start + 1
        big = end
        for i in range(end - start):
            if xList[small] <= value:
                xList[small], xList[valuePosition] = xList[valuePosition], xList[small]
                valuePosition = small
                small += 1
            else:
                xList[small], xList[big] = xList[big], xList[small]
                big -= 1
        return valuePosition
    
    
    if __name__ == '__main__':
        print quickSort([1, ])
        print quickSort([2, 1])
        print quickSort([2, 2, 1])
        print quickSort([2, 3, 4, 1])
        print quickSort([1, 2, 4, 3])
        import random
        randomList = range(10)
        random.shuffle(randomList)
        print 'random:', randomList
        print quickSort(randomList)

      

  • 相关阅读:
    遗传算法的理解
    使用Grub Rescue 修复MBR
    java 虚拟机与并发处理几个问题简要(二)
    java 虚拟机与并发处理几个问题简要(一)
    Fence Repair POJ
    Best Cow Line---POJ 3617(贪心)
    迷宫的最短路径
    最大子段和
    Lake Counting --POJ 2386
    Ants POJ
  • 原文地址:https://www.cnblogs.com/yesuuu/p/7414185.html
Copyright © 2011-2022 走看看