Quick Sort
Quicksort Explained
Quicksort is a divide-and-conquer sorting algorithm that works by selecting a pivot element, partitioning the array so all smaller elements go left and all larger go right, then recursively sorting each partition.
Code Snippets
Quicksort (Main Function)
def quicksort(array: list[int], start: int = 0, end: int = None) -> None:
"""Sort array in-place using quicksort with Lomuto partition."""
if end is None:
end = len(array) - 1
if start >= end:
return
pivot_final_index = partition(array, start, end)
quicksort(array, start, pivot_final_index - 1)
quicksort(array, pivot_final_index + 1, end)
Lomuto Partition
def partition(array: list[int], start: int, end: int) -> int:
"""Partition array around the last element as pivot.
After partition:
- All elements left of pivot_final_index are <= pivot
- All elements right of pivot_final_index are > pivot
"""
pivot_value = array[end]
insert_position = start
for current_index in range(start, end):
if array[current_index] <= pivot_value:
array[insert_position], array[current_index] = (
array[current_index], array[insert_position]
)
insert_position += 1
# Place pivot in its final sorted position
array[insert_position], array[end] = array[end], array[insert_position]
return insert_position
Why Pivot Selection Matters
Quicksort's efficiency depends entirely on how well the pivot splits the array:
- Perfect split (pivot is the median): Each level halves the array — O(n log n)
- Worst split (pivot is always min or max): One partition has n-1 elements — O(n^2)
The worst case happens when the array is already sorted and you always pick the first or last element as pivot.
Mitigation strategies:
- Median-of-three: Pick the median of the first, middle, and last elements
- Random pivot: Select a random element — makes worst-case astronomically unlikely
- Introsort: Switch to heapsort if recursion depth exceeds 2 log(n) — guaranteed O(n log n)
When Quicksort Beats Mergesort
Both are O(n log n) on average, but quicksort wins in practice for several reasons:
Cache locality: Quicksort operates on contiguous memory, making excellent use of CPU cache lines. Mergesort's merge step accesses two separate arrays, causing more cache misses.
In-place sorting: Quicksort needs only O(log n) extra space for the recursion stack. Mergesort requires O(n) auxiliary space.
When mergesort wins: Mergesort guarantees O(n log n) worst case, is stable (preserves equal-element order), and works well with linked lists.
Practical Takeaways
- Use quicksort (or introsort) for general-purpose in-memory sorting
- Use mergesort when you need stability or guaranteed worst-case performance
- Always randomize pivot selection in production
- For small subarrays (n < 16), switch to insertion sort — lower constant factors