

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 4
click for more info
Not enough gems
Cost: 6 gems
1: Sorting Algorithms
incomplete
2: Bubble Sort
incomplete
3: Bubble Sort Big O
incomplete
4: Why Bubble Sort?
incomplete
5: Merge Sort
incomplete
6: Merge Sort Big O
incomplete
7: Why Merge Sort?
incomplete
8: Insertion Sort
incomplete
9: Insertion Sort Big O
incomplete
10: Why Use Insertion Sort?
incomplete
11: Quicksort
incomplete
12: Quicksort Big O
incomplete
13: Fixing Quicksort
incomplete
14: Why Use Quicksort?
incomplete
15: Selection Sort
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
On average, quicksort has a Big O of O(n*log(n)). In the worst case, and assuming we don't take any steps to protect ourselves, it can degrade to O(n^2). partition() has a single for-loop that ranges from the lowest index to the highest index in the array. By itself, the partition() function is O(n). The overall complexity of quicksort is dependent on how many times partition() is called.
Worst case: The input is already sorted. An already sorted array results in the pivot being the largest or smallest element in the partition each time, so each call only peels off one element. That's n levels of recursion, each doing up to n work in partition().
Best case: The pivot is the middle element of each sublist, which results in only log(n) levels of recursion, each doing n total work in partition().
def quick_sort(nums: list[int], low: int, high: int) -> None:
if low < high:
p = partition(nums, low, high)
quick_sort(nums, low, p - 1)
quick_sort(nums, p + 1, high)
def partition(nums: list[int], low: int, high: int) -> int:
pivot = nums[high]
i = low
for j in range(low, high):
if nums[j] < pivot:
nums[i], nums[j] = nums[j], nums[i]
i += 1
nums[i], nums[high] = nums[high], nums[i]
return i