快速排序算法
算法介绍
快速排序算法是目前最快的排序算法,其主旨是将一个数移动到一个左边的数均比他小(大),右边的数均比他大(小)的位置,之后对这个数的左边再次进行同样操作。与二叉查找有异曲同工之妙。
代码
def KSPX(start1,end1):
global ybsb
#print("a = ",a)
#print("start1=", start1, "end1=", end1)
#MOT(a,start1, int(len(a) / 2), end1)
if start1 >= end1:
return 'Ok,The End'
#确定起始的时候要交换的两个元素和中间的标尺
start = start1
end = end1
splitIndex = start#曲轴
while 1:
#print("start = ",start,"end = ",end,"a[start] = ",a[start],"a[end] = ",a[end])
if a[start] > a[end]:
m = a[end]
a[end] = a[start]
a[start] = m#交换
if splitIndex == start:
splitIndex = end
start = start + 1
else:
splitIndex = start
end = end - 1
else:
if splitIndex == start:
splitIndex = start
end = end - 1
else:
splitIndex = end
start = start + 1
ybsb = ybsb + 1
if end <= start:
break
#print("splitIndex=",splitIndex, ",end=",end, ",a=",a)
if splitIndex - 1 > start1:
KSPX(start1, splitIndex - 1)#递归排序前面的
if end1 > splitIndex + 1:
KSPX(splitIndex + 1, end1)#递归排序后面的
a = [1,8,4,482,4196,231,132564,131,244235,4681,213,12,1372,3,23491,21498,2947,2018645139,
175,174,2309,1863,297,18114]
end = len(a) - 1#上标
start = 0#下标
ybsb = 0
KSPX(start,end)
print(a, ybsb,"THE End")
快排、冒泡、希尔的排序测试
数列:1,8,4,482,4196,231,132564,131,244235,4681,213,12,1372,3,23491,21498,2947,2018645139,
175,174,2309,1863,297,18114
冒泡:(可见的结果)
25*25 = 625次
希尔:
172次
快速排序:
110次
经比较,快排次数<希尔次数<冒泡次数