快速排序算法
基本思想
(1)选定pivot中心轴
(2)将大于pivot的数字放在pivot的右边
(3)将小于pivot的数字放在pivot的左边
(4)分别对左右子序列重复前三步操作
代码实现
""
快速排序
1.选定pivot中心轴
2.将大于pivot的数字放在pivot的右边
3.将小于pivot的数字放在pivot的左边
"""
# left是左边索引,right是右边索引
def QSort(arry, left, right):
if left >= right:
return
l = left
r = right
pivot = arry[left] # 选取pivot
while l < r:
# 首先右指针从右往左开始寻找,将大于pivot的数字放在pivot的右边,得到右子序列都比pivot大
while l < r and arry[r] >= pivot:
# 右指针向左移动,索引减1
r -= 1
# 右指针指的值大于pivot的值,需要将右指针上的值赋给左指针
arry[l] = arry[r]
# 左指针从左往右开始寻找,将小于pivot的数字放在pivot的左边,得到左子序列都比pivot小
while l < r and arry[l] < pivot:
# 左指针向右移动,索引加1
l += 1
# 右指针指的值大于pivot的值,需要将右指针上的值赋给左指针
arry[r] = arry[l]
arry[l] = pivot
# 左子序列的新的pivot索引值应该为上一次pivot索引值 - 1
QSort(arry, left, r - 1) # 对左子序列进行重复快排的操作
# 右子序列的新的pivot索引值应该为上一次pivot索引值 + 1
QSort(arry, r + 1, right) # 对右子序列进行重复快排的操作
return arry
arr = [4, 5, 8, 2, 3, 1, 9, 7]
result = QSort(arr, 0, len(arr) - 1)
print(result)
快速排序的平均时间复杂度为O(nlogn),最坏情况是O(n2),最好情况为O(nlogn)