Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Median of Medians Implementation in C#

19 min readadvanced
Website QA and SEO audits

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 (BFPRT) is the pivot rule that makes quickselect linear in the WORST case, not just on average. Split the array into groups of five, sort each group, take each group's median, recursively select the median of those medians, and partition on it. That pivot is guaranteed to have at least ~30% of elements on each side, so T(n) = T(n/5) + T(7n/10) + O(n) = O(n). That bound assumes DISTINCT keys. With a two-way partition on strict <, an input of many equal keys puts every equal element on the greater side, so the range shrinks by exactly one element per step and the whole thing goes quadratic or worse -- the opposite of what you came for, on the cheapest input an attacker can send. Production BFPRT partitions three ways (< pivot / == pivot / > pivot, the Dutch-national-flag split) and returns immediately when k falls inside the equal band. Every snippet below shows the two-way core for clarity; swap in a three-way partition before you rely on the worst-case bound. You reach for it when a random pivot is unacceptable: adversarial or attacker-supplied input, a hard real-time deadline, or a provable bound you have to defend in review.

Median of Medians in C#: what you actually reach for

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.

C# implementation

Take Span<T> (or ReadOnlySpan<T> plus a destination) rather than T[] -- a[] forces callers with a segment to copy. Prefer a struct comparer under where TComparer : IComparer<T>, allocatable-free and devirtualised by the JIT, over a Comparison<T> delegate. Reviewers want the tuple swap (a[i], a[j]) = (a[j], a[i]), an ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual style guard on k, and no LINQ anywhere in the recursion. Marking the recursive helper static local or private static avoids a closure capture.
csharp
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 Free

The C#-specific 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 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.

Performance in C#, beyond the O(n)

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. The asymptotic cost is the same in every language, O(n) time and O(n) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Median of Medians between languages.

Real-World Applications

Median of Medians applies wherever its problem shape appears in your own code. In C#, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Median of Medians helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Median of Medians appears frequently in final rounds at FAANG-level companies and system design interviews. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Median of Medians over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Median of Medians to build pattern recognition. In C#, demonstrate proficiency with LINQ and async patterns to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic C# code that is both correct and maintainable.

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).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

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 trial

Studying for this? Student discounts on developer tools are collected on Noizz, tool by tool.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

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.