Skip to content

Instantly share code, notes, and snippets.

@Per48edjes
Created April 14, 2023 20:17
Show Gist options
  • Save Per48edjes/b82aee22469491aecadb7e2cade70d55 to your computer and use it in GitHub Desktop.
Save Per48edjes/b82aee22469491aecadb7e2cade70d55 to your computer and use it in GitHub Desktop.
Leetcode 912. Sort an Array (Randomized QuickSort)
# Let's implement Randomized QuickSort!
import random
class Solution:
# O(n)
def partition(self, nums: List[int], l: int, r: int) -> int:
# Choose random pivot, put it first in the array
random_idx = random.choice(range(l, r + 1))
nums[l], nums[random_idx] = nums[random_idx], nums[l]
pivot = l
# Maintain loop invariant: for all non-pivot elements, everything
# 1. before i is is < nums[pivot]
# 2. between i, j is > nums[pivot]
# 3. after j is yet to be processed
i, j = l, l + 1
while j <= r:
if nums[j] < nums[pivot]:
nums[i + 1], nums[j] = nums[j], nums[i + 1]
i += 1
j += 1
# Switch pivot into correct place
nums[i], nums[pivot] = nums[pivot], nums[i]
return i
# O(n log n) expected time, O(log n) space
def quicksort(self, nums: List[int], l: int, r: int) -> None:
if 0 <= l < r < len(nums):
p = self.partition(nums, l, r)
self.quicksort(nums, l, p - 1)
self.quicksort(nums, p + 1, r)
def sortArray(self, nums: List[int]) -> List[int]:
self.quicksort(nums, 0, len(nums)-1)
return nums
@Per48edjes
Copy link
Author

Per48edjes commented Apr 14, 2023

Note: Leetcode will make sure to test the worst cases that make QuickSort run in $O(n^2)$ time! So this will TLE, for example, when all of the large number of elements are uniformly the same.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment