【算法导论】第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)

 

  

 

posted on 2017-08-22 23:03  yesuuu  阅读(137)  评论(0编辑  收藏  举报

导航