Partition Values with Quicksort
Core idea
Quicksort selects a pivot and partitions values around it, then recursively sorts the smaller and larger groups. This teaching version uses three new lists and keeps equal values separate. Balanced splits give O(n log n) time; repeated highly uneven splits give O(n²) time and linear recursion depth. It is not the in-place partition algorithm.
a = [4, 2, 4, 1, 8]p = a[0]print([x for x in a if x < p])print([x for x in a if x == p])print([x for x in a if x > p])Every integer belongs to exactly one partition; duplicates remain.
Recursive sorting
def quick(a): if len(a) <= 1: return a[:] p = a[0] return (quick([x for x in a if x < p]) + [x for x in a if x == p] + quick([x for x in a if x > p]))print(quick([5, 2, 5, 1]))The pivot group is excluded from recursion, so both recursive inputs shrink.
Common mistake
Picking the first item on sorted input is a bad pivot policy. Do not apply this implementation to huge inputs; recursion and temporary lists can exhaust resources.
Practice
Trace partitions for [1, 2, 3, 4] and [3, 3, 3]. Compare recursive depth.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Quicksort
Check your understanding of quicksort.
What is printed?
print([x for x in [3,1,3,5] if x==3])What is printed?
a=[1,2,3,4]print(len([x for x in a if x>a[0]]))What ensures recursive progress?
Worst-case quicksort time with repeated extreme pivots?