Quick Sort
Partition-based sorting that picks a pivot and recursively sorts subarrays in-place.
The Mathematics
Partition-based sorting, recurrence analysis, and average-case complexity
Core Idea
Quick Sort selects a pivot element and partitions the array so that all elements pivot are on the left and all elements pivot are on the right. The pivot is then in its final sorted position.
Recurrence Relation
If the pivot lands at position , we get two subproblems of sizes and . Partitioning takes :
Worst case ( every time, e.g., already sorted input):
Average case (pivot lands roughly in the middle):
Lomuto Partition Scheme
Choose the last element as pivot. Maintain index such that and :
Finally, swap to place the pivot at index .
Why Quick Sort Is Fast in Practice
Despite worst case, Quick Sort is often faster than Merge Sort due to: (1) in-place partitioning (no extra memory), (2) cache-friendly sequential access, and (3) randomized pivot selection makes worst case extremely unlikely — expected with high probability.
See It Work
Sorting [6, 3, 8, 2, 5, 1] via pivot partitioning
Start with unsorted array. Quick Sort picks a pivot and partitions elements around it.
The Code
Mapping partition logic to Python with Lomuto scheme
Mathematical Formulation
Base case: subarrays of size ≤ 1 are already sorted
Partition returns the final index of the pivot
Two recursive calls on subarrays left and right of pivot
Lomuto partition: choose the last element as pivot
Move elements ≤ pivot to the left partition
Place pivot in its final sorted position
Python Implementation
def quick_sort(A, lo=0, hi=None):
if hi is None: hi = len(A) - 1
if lo < hi:
p = partition(A, lo, hi) # Partition
quick_sort(A, lo, p - 1) # Sort left
quick_sort(A, p + 1, hi) # Sort right
def partition(A, lo, hi):
pivot = A[hi] # Choose last as pivot
i = lo
for j in range(lo, hi): # Scan elements
if A[j] <= pivot:
A[i], A[j] = A[j], A[i] # Swap to left
i += 1
A[i], A[hi] = A[hi], A[i] # Place pivot
return i