Loading...
A deterministic selection algorithm that finds the k-th smallest element in linear time O(n) by guaranteeing a balanced pivot.
Current Active Subset (n=0)
1function select(A, k):2 if length(A) <= 5: return sort(A)[k]3 groups = divide A into groups of 54 medians = [median(g) for g in groups]5 pivot = select(medians, length(medians)/2)6 L, E, G = partition A around pivot7 if k < length(L): return select(L, k)8 if k < length(L) + length(E): return pivot9 return select(G, k - length(L) - length(E))By choosing the median of group (size 5) medians, we guarantee that the pivot is at least greater than 30% and less than 30% of the elements. This prevents the "unlucky" pivots that cause O(n^2) in basic Quickselect.