Find the Kth largest without fully sorting. Partition around a pivot, then recurse into only the side that must contain the answer, throwing the other half away each time.
Partition puts the pivot in its final sorted slot: everything smaller left, larger right. If that slot is exactly the target index, done. Otherwise recurse into only the half that holds the target.
n-k when sorted ascendingint partition(vector<int>& a, int lo, int hi) {
int pivot = a[hi], i = lo; // Lomuto: pivot = last
for (int j = lo; j < hi; j++)
if (a[j] < pivot) swap(a[i++], a[j]);
swap(a[i], a[hi]); // pivot to its final slot
return i;
}
int quickSelect(vector<int>& a, int lo, int hi, int target) {
if (lo == hi) return a[lo];
int p = partition(a, lo, hi);
if (p == target) return a[p]; // pivot IS the answer
if (target < p) return quickSelect(a, lo, p - 1, target);
return quickSelect(a, p + 1, hi, target); // one side only
}
int findKthLargest(vector<int>& a, int k) {
return quickSelect(a, 0, a.size() - 1, a.size() - k);
}
Each step halves the range: n + n/2 + n/4 + … ≈ 2n.
Pathological pivots. Random or median-of-medians pivot avoids it.
In-place partition; recursion tail-optimizes to iterative.