#! /usr/bin/env python
#coding=utf-8
import random
#快排的普通版本
def QuickSort(a, p, r):
if p<r:
q=Partition(a, p, r)
QuickSort(a, p, q-1)
QuickSort(a, q+1, r)
def Partition(a, p, r):
x=a[r]
i=p-1
for j in range(p, r):
'''如果a[j]>x,则只需将j的值加1即可使循环不变量继续保持; 如果a[j]<=x,则将下标i的值加1,并交换a[i]和a[j],再将 j的值加1.此时循环不变量同样得到保持'''
if a[j]<=x:
i=i+1
a[i], a[j]=a[j], a[i]
a[i+1], a[r]=a[r], a[i+1]
return i+1
#快排的随机化版本
def RandomPartition(a, p, r):
i=random.randint(p, r) #生成的随机数为p=<i<=r
a[r], a[i]=a[i], a[r]
return Partition(a, p, r)
def RandomQuickSort(a, p, r):
if p<r:
q=RandomPartition(a, p, r)
RandomQuickSort(a, p, q-1)
RandomQuickSort(a, q+1, r)
if __name__ == '__main__':
a1 = [11, 4, 33, 100, -4, 6, 8]
a2 = [8,10,9,6,4,16,5,13,26,18,2,45,34,23,1,7,3]
QuickSort(a1, 0, len(a1)-1)
print a1
RandomQuickSort(a2, 0, len(a2)-1)
print a2
运行结果:
[-4, 4, 6, 8, 11, 33, 100]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 13, 16, 18, 23, 26, 34, 45]