def Partition(arr, low, high):
pivot = arr[low] # 将第一个元素设置为枢纽
while low < high:
while low < high and arr[high] >= pivot:
high -= 1
arr[low] = arr[high]
while low < high and arr[low] <= pivot:
low += 1
arr[high] = arr[low]
arr[low] = pivot
return low # 返回枢纽最终的存放位置
def quickSort(arr, low, high):
if low < high:
pivotpos = Partition(arr, low, high) # 划分
# 对左右两个子数组递归进行划分
quickSort(arr, low, pivotpos-1)
quickSort(arr, pivotpos+1, high)
if __name__ == '__main__':
array = [1,2,3,5,2,5,7,4,21,6]
quickSort(array, 0, len(array)-1)
print(array)
三路快排
import random
def swap(arr, i, j):
arr[i], arr[j] = arr[j], arr[i]
def Partition(arr, low, high):
swap(arr, low, random.randint(low, high))
pivot = arr[low] # 将第一个元素设置为枢纽
# 设置小于pivot元素的区间的右端点p1,大于pivot元素的集合区间的左端点p2
# 当前元素cur
p1, p2, cur = low, high, low
while cur <= p2:
if arr[cur] < pivot:
swap(arr, p1, cur)
p1 += 1
cur += 1
elif arr[cur] > pivot:
swap(arr, cur, p2)
p2 -= 1
else:
cur += 1
print(p1, p2)
print(arr)
return p1, p2 # 返回的是pivot元素的集合的区间左端点和右端点
def quickSort(arr, low, high):
if low < high:
pivotposl, pivotposr = Partition(arr, low, high) # 划分
# 对左右两个子数组递归进行划分
quickSort(arr, low, pivotposl-1)
quickSort(arr, pivotposr+1, high)
if __name__ == '__main__':
array = [5,2,3,1,2,5,7,4,21,6]
size = len(array)
if size >= 2:
quickSort(array, 0, size-1)
print(array)