Median of Medians Implementation in C#
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Median of Medians runs in O(n) time and O(n) space, in C# as in every other language.
- ✓There is no nth-element in the BCL. Array.Sort and List<T>.Sort are introsort; MemoryExtensions.Sort (System) sorts a Span<T> in place; Enumerable.OrderBy is a stable, fully materialising sort, so OrderBy(...).ElementAt(k) is O(n log n) plus an allocation of the whole sequence.
- ✓Take Span<T> (or ReadOnlySpan<T> plus a destination) rather than T[] -- a[] forces callers with a segment to copy.
- ✓The C# trap: Span<T> is a ref struct, so it cannot be captured in a lambda, stored in a field, held across await, or put in a List<Span<T>>.
- ✓The JIT emits a separate specialised body for every value-type T -- no boxing, and Comparer<T>.Default.Compare inlines when T implements IComparable<T> -- while all reference-type T share one canonical body reached through a runtime dictionary lookup.
What Median of Medians actually is
Median of Medians in C#: what you actually reach for
C# implementation
using System;
public static class Selection
{
private static void Ins<T>(Span<T> a) where T : IComparable<T>
{
for (int i = 1; i < a.Length; i++)
{
T v = a[i];
int j = i - 1;
while (j >= 0 && a[j].CompareTo(v) > 0) { a[j + 1] = a[j]; j--; }
a[j + 1] = v;
}
}
private static int PivotIndex<T>(Span<T> a) where T : IComparable<T>
{
int n = a.Length;
if (n <= 5) { Ins(a); return n / 2; }
int m = 0;
for (int g = 0; g < n; g += 5)
{
int e = Math.Min(g + 5, n);
Ins(a.Slice(g, e - g));
int mid = g + (e - g) / 2;
(a[m], a[mid]) = (a[mid], a[m]);
m++;
}
SelectNth(a.Slice(0, m), m / 2);
return m / 2;
}
/// <summary>Reorders the span and returns its k-th smallest element.</summary>
public static T SelectNth<T>(Span<T> a, int k) where T : IComparable<T>
{
while (a.Length > 1)
{
int p = PivotIndex(a);
(a[0], a[p]) = (a[p], a[0]);
T pv = a[0];
int i = 0;
for (int j = 1; j < a.Length; j++)
if (a[j].CompareTo(pv) < 0) { i++; (a[i], a[j]) = (a[j], a[i]); }
(a[0], a[i]) = (a[i], a[0]);
if (k == i) return a[i];
if (k < i) { a = a.Slice(0, i); }
else { a = a.Slice(i + 1); k -= i + 1; }
}
return a[0];
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe C#-specific trap
Performance in C#, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which C# type or library should I use for Median of Medians?
There is no nth-element in the BCL. Array.Sort and List<T>.Sort are introsort; MemoryExtensions.Sort (System) sorts a Span<T> in place; Enumerable.OrderBy is a stable, fully materialising sort, so OrderBy(...).ElementAt(k) is O(n log n) plus an allocation of the whole sequence. Comparer<T>.Default resolves IComparable<T> without boxing for value types, and System.Buffers.ArrayPool<T>.Shared gives you a scratch buffer if you ever need one. Write BFPRT against Span<T> so callers can hand you a slice with no copy.
What is the most common C# mistake when implementing Median of Medians?
Span<T> is a ref struct, so it cannot be captured in a lambda, stored in a field, held across await, or put in a List<Span<T>>. The natural refactor -- collect the five-element group spans into a list, then select over them -- simply will not compile, and the usual escape is to copy into a T[], which quietly turns the in-place O(1) recursion into an allocating one. Reaching for stackalloc instead does not save you, and not only because stackalloc needs where T : unmanaged (CS0208 otherwise, so the generic version will not even compile): a stackalloc int[5] inside the group loop is released when the METHOD returns, not at the end of the iteration, so it accumulates n/5 buffers on a 1 MB stack and throws StackOverflowException, which no try/catch can recover.
How does Median of Medians actually perform in C#?
The JIT emits a separate specialised body for every value-type T -- no boxing, and Comparer<T>.Default.Compare inlines when T implements IComparable<T> -- while all reference-type T share one canonical body reached through a runtime dictionary lookup. A Comparison<T> delegate is never inlined; a struct comparer passed as a generic type argument is. Span indexing elides the bounds check in a for (i = 0; i < span.Length; i++) shape but not when the bound is a captured local. Tiered compilation starts in tier 0: real native code, but JITted with optimisations off, typically two to four times slower than tier 1. A long-running partition loop is rescued by on-stack replacement rather than by the method being re-entered, so measure with BenchmarkDotNet (which warms up) or the first run's numbers are noise. Time complexity is O(n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? Student discounts on developer tools are collected on Noizz, tool by tool.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.