Sorting & Selection Hard
Quickselect: Median in Linear Time
Median.java uses a first-element pivot and two inward scans to place one pivot at its final rank, then recurses only toward the vector's middle index.
Trace input
Bounded JSONEdit the lesson input, then build a deterministic source-linked trace.
Source scenarios
Complexity
BestO(n)
AverageO(n) expected on random input
WorstO(n²)
SpaceO(n) recursive stack in the worst case
Array state
Follow the active comparisons and writes.
Current operation
Trace stateReady to explore
Source behavior & common mistakes
Trace the source's in-place partition steps on an odd-sized integer vector. Follow the pivot identity, strict comparisons, swap order, and the recursive search for index floor(n / 2).
- The source requires an odd-sized vector and selects the global index size / 2.
- Each call partitions around its first element; the equal-key comparisons are strict.
- The helper performs one partition, not a full quicksort; only one side is searched next.
- Partition swaps mutate the original vector and move element identities with their values.
- A one-element vector reaches the source helper's first out-of-range scan read; the trace preserves that Java exception.
Algorithm code
JavaMedian.java (pinned repository source)Step linked
The highlighted line follows the current step.
Ready to begin
Press Play to see what happens.
Detailed execution
Snapshot 1 / 1