Foundation · Module 4 · Lesson 5

Quick Sort & Quickselect

Partition around a pivot and recurse selectively.

15–25 min readLesson 23 of 123 Interactive Lab

Lesson 23 of 123

1d streak

Interactive Visualization

Trace the algorithm state by state

Change the inputs, run an operation, and connect each visible state change to the explanation below.

Interactive algorithm lab

Quick Sort

Partition around a pivot and recurse

Step 1 / 21

Input size

6

Active cells

2

Fixed pivots

0

Progress

1/21

8
0
3
1
6
2
2
3
7
4
1
5
range [0, 5]

Why this step happens

8 remains in the > pivot region.

Invariant to protect

Indexes 0…-1 are ≤ 1; indexes 0…-1 are > 1.

Theory lesson · Step-by-step

Understand Quick Sort & Quickselect

Partition around a pivot and recurse selectively.

Worked approach

Trace the reasoning step by step

  1. 1Choose a pivot.
  2. 2Partition values around it.
  3. 3For Quick Sort, recurse into both sides.
  4. 4For Quickselect, recurse only into the side containing rank k.

Concrete example

Partition [4, 1, 3, 2] around pivot 3.

  1. 1Move values < 3 left: [1,2].
  2. 2Place pivot after them.
  3. 3Values > 3 remain right: [4].

Pivot 3 reaches its final rank; quickselect recurses into only one side.

What must remain true (Loop Invariant)

After partitioning, values left of the pivot satisfy the left condition and values right satisfy the right condition.

Cost Model

Complexity & Trade-offs

Sort
Average O(n log n); worst O(n²)
Average O(log n) stack
Include stability and input shape when comparing sorts.

When to use it

  • Creating order before searching, grouping, deduplicating, or scanning.
  • Selecting records using stability, memory, and input-shape constraints.
  • Turning pairwise decisions into monotonic scans.

Common mistakes

  • Comparing time alone while ignoring stability and auxiliary memory.
  • Breaking duplicate order when stability is required.
  • Quoting average performance without worst-case behavior.

Practice prompts

  • Reproduce the worked Quick Sort & Quickselect example without looking at the trace.
  • Change one input condition and explain whether the Quick Sort & Quickselect invariant still holds.
  • Implement the approach, derive its cost, and compare it with a straightforward baseline.

Mastery check

Can you derive it instead of memorizing it?

State the invariant before looking at code.
Explain why every transition is safe.
Construct a worst-case input.
Name one alternative and its trade-off.