Skip to content

Instantly share code, notes, and snippets.

@DiegoGallegos4
Last active April 15, 2019 05:59
Show Gist options
  • Save DiegoGallegos4/acffda08a7ca8b1607574df447762488 to your computer and use it in GitHub Desktop.
Save DiegoGallegos4/acffda08a7ca8b1607574df447762488 to your computer and use it in GitHub Desktop.
Divide and Conquer: Quicksort
def partition(A, left, right):
pivot, j = A[left], left
for i in range(left + 1, right + 1):
if A[i] <= pivot:
j += 1
A[i], A[j] = A[j], A[i]
A[left], A[j] = A[j], A[left]
return j
def quicksort(A, left, right):
"""
Running time:
O(nlogn)
pivot = A[left]
move i from left + 1 to right maintaining the following invariant:
A[k] <= x ∀ left + 1 <= k <= j
A[k] > x ∀ j + 1 <= k <= i
then move A[left] to its final position
"""
if left > right:
return
k = random.randint(left, right)
A[k], A[left] = A[left], A[k]
pivot = partition(A, left, right)
quicksort(A, left, pivot - 1)
quicksort(A, pivot + 1, right)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment