Quickselect for the Kth Element
After partitioning, continue only in the part containing the desired rank.
Core Intuition & How It Works
Quickselect finds the Kth smallest or largest element in an unsorted array without sorting the whole array. After partitioning around a pivot, it recurses into only the one side containing index K, achieving O(n) expected time.
In the Byte Sized Algorithms interactive classroom, you can step forward and backward through this algorithm with your keyboard while watching the visual diagram, memory state, and highlighted pseudocode update together.
Time & Space Complexity
| Metric | Complexity |
|---|---|
| Time Complexity | O(n) expected, O(n²) worst |
| Space Complexity | O(1) iterative |
| Topic Chapter | Chapter 9: Sorting & Selection |
| Difficulty Level | Intermediate |
Key Pattern to Recognize
Randomize the pivot before partitioning so adversarial inputs cannot force quadratic partitions.
Common Pitfalls & Edge Cases
Recursing into both sides (which turns Quickselect into Quicksort) or confusing 1-based Kth rank with 0-based array index.
Real-World & Technical Interview Applications
Exact medians, order statistics, K closest points, and C++ std::nth_element.