Skip to content

Instantly share code, notes, and snippets.

@willshw
Last active August 25, 2021 03:53
Show Gist options
  • Save willshw/2fbdddda04ee2b62d62806e18be0aefb to your computer and use it in GitHub Desktop.
Save willshw/2fbdddda04ee2b62d62806e18be0aefb to your computer and use it in GitHub Desktop.
Quick Sort
def quickSort(self, A, start, end):
  if start >= end:
      return

  left, right = start, end
  # key point 1: pivot is the value, not the index
  pivot = A[(start + end) // 2]

  # key point 2: every time you compare left & right, it should be 
  # left <= right not left < right
  while left <= right:
      while left <= right and A[left] < pivot:
          left += 1
      while left <= right and A[right] > pivot:
          right -= 1
      if left <= right:
          A[left], A[right] = A[right], A[left]
          left += 1
          right -= 1

  self.quickSort(A, start, right)
  self.quickSort(A, left, end)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment