快速排序

  1. class Solution:
  2. # @param {int[]} A an integer array
  3. # @return nothing
  4. def sortIntegers2(self, A):
  5. # Write your code here
  6. self.quickSort(A, 0, len(A) - 1)
  7. def quickSort(self, A, start, end):
  8. if start >= end:
  9. return
  10. left, right = start, end
  11. # key point 1: pivot is the value, not the index
  12. pivot = A[(start + end) // 2]
  13. # key point 2: every time you compare left & right, it should be
  14. # left <= right not left < right
  15. while left <= right:
  16. while left <= right and A[left] < pivot:
  17. left += 1
  18. while left <= right and A[right] > pivot:
  19. right -= 1
  20. if left <= right:
  21. A[left], A[right] = A[right], A[left]
  22. left += 1
  23. right -= 1
  24. self.quickSort(A, start, right)
  25. self.quickSort(A, left, end)