1. def Partition(arr, low, high):
  2. pivot = arr[low] # 将第一个元素设置为枢纽
  3. while low < high:
  4. while low < high and arr[high] >= pivot:
  5. high -= 1
  6. arr[low] = arr[high]
  7. while low < high and arr[low] <= pivot:
  8. low += 1
  9. arr[high] = arr[low]
  10. arr[low] = pivot
  11. return low # 返回枢纽最终的存放位置
  12. def quickSort(arr, low, high):
  13. if low < high:
  14. pivotpos = Partition(arr, low, high) # 划分
  15. # 对左右两个子数组递归进行划分
  16. quickSort(arr, low, pivotpos-1)
  17. quickSort(arr, pivotpos+1, high)
  18. if __name__ == '__main__':
  19. array = [1,2,3,5,2,5,7,4,21,6]
  20. quickSort(array, 0, len(array)-1)
  21. print(array)

三路快排

  1. import random
  2. def swap(arr, i, j):
  3. arr[i], arr[j] = arr[j], arr[i]
  4. def Partition(arr, low, high):
  5. swap(arr, low, random.randint(low, high))
  6. pivot = arr[low] # 将第一个元素设置为枢纽
  7. # 设置小于pivot元素的区间的右端点p1,大于pivot元素的集合区间的左端点p2
  8. # 当前元素cur
  9. p1, p2, cur = low, high, low
  10. while cur <= p2:
  11. if arr[cur] < pivot:
  12. swap(arr, p1, cur)
  13. p1 += 1
  14. cur += 1
  15. elif arr[cur] > pivot:
  16. swap(arr, cur, p2)
  17. p2 -= 1
  18. else:
  19. cur += 1
  20. print(p1, p2)
  21. print(arr)
  22. return p1, p2 # 返回的是pivot元素的集合的区间左端点和右端点
  23. def quickSort(arr, low, high):
  24. if low < high:
  25. pivotposl, pivotposr = Partition(arr, low, high) # 划分
  26. # 对左右两个子数组递归进行划分
  27. quickSort(arr, low, pivotposl-1)
  28. quickSort(arr, pivotposr+1, high)
  29. if __name__ == '__main__':
  30. array = [5,2,3,1,2,5,7,4,21,6]
  31. size = len(array)
  32. if size >= 2:
  33. quickSort(array, 0, size-1)
  34. print(array)