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

Median of Medians Implementation in Java

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 Java as in every other language.
  • ✓java.util has no selection method. Arrays.sort(int[]) is a dual-pivot quicksort over primitives (modern JDKs add a heapsort fallback so a killer input degrades to n log n instead of quadratic); Arrays.sort(T[], Comparator) is TimSort.
  • ✓Primitive arrays, not Integer[] or List<Integer> -- boxing in an inner comparison loop is the first review comment.
  • ✓The Java trap: If you generalise to T[] with a Comparator, the reflexive shortcut (a, b) -> a - b overflows for large or negative ints, so comparison stops being transitive.
  • ✓Integer[] costs a pointer dereference plus a 16-byte header per element and destroys cache locality; int[] keeps the partition scan streaming.

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 Java: what you actually reach for

java.util has no selection method. Arrays.sort(int[]) is a dual-pivot quicksort over primitives (modern JDKs add a heapsort fallback so a killer input degrades to n log n instead of quadratic); Arrays.sort(T[], Comparator) is TimSort. PriorityQueue<E> handles small k in O(n log k). IntStream.of(a).sorted() stays primitive -- it buffers into an int[] and calls Arrays.sort -- so the cost is a full copy of the array plus per-element pipeline dispatch, not boxing; you pay boxing only when you cross to Stream<Integer> (.boxed(), or a List<Integer> source), and either way it is an O(n log n) sort where you wanted an O(n) selection. So BFPRT is hand-written, over int[] or long[] with an explicit (lo, hi) range, exactly the way Arrays' own private helpers are shaped.

Java implementation

Primitive arrays, not Integer[] or List<Integer> -- boxing in an inner comparison loop is the first review comment. Use lo + (hi - lo) / 2 or (lo + hi) >>> 1 for midpoints, never (lo + hi) / 2, because the JDK's own binarySearch shipped that overflow bug for years. Private static helpers taking (int[] a, int lo, int hi) with hi exclusive matches java.util conventions. Reviewers also want Objects.checkIndex(k, a.length) instead of a bare array access to produce the right exception type.
java
public final class Selection {
    private Selection() {}

    private static void ins(int[] a, int lo, int hi) {
        for (int i = lo + 1; i < hi; i++) {
            int v = a[i], j = i - 1;
            while (j >= lo && a[j] > v) { a[j + 1] = a[j]; j--; }
            a[j + 1] = v;
        }
    }

    private static int pivotIndex(int[] a, int lo, int hi) {
        int n = hi - lo;
        if (n <= 5) { ins(a, lo, hi); return lo + n / 2; }
        int m = lo;
        for (int g = lo; g < hi; g += 5) {
            int e = Math.min(g + 5, hi);
            ins(a, g, e);
            int mid = g + (e - g) / 2;
            int t = a[m]; a[m] = a[mid]; a[mid] = t;
            m++;
        }
        return select(a, lo, m, lo + (m - lo) / 2);
    }

    /** Reorders a[lo,hi) so a[k] is the k-th smallest; returns k. */
    public static int select(int[] a, int lo, int hi, int k) {
        while (hi - lo > 1) {
            int p = pivotIndex(a, lo, hi);
            int t = a[lo]; a[lo] = a[p]; a[p] = t;
            int pv = a[lo], i = lo;
            for (int j = lo + 1; j < hi; j++) {
                if (a[j] < pv) { i++; t = a[i]; a[i] = a[j]; a[j] = t; }
            }
            t = a[lo]; a[lo] = a[i]; a[i] = t;
            if (k == i) return k;
            if (k < i) hi = i; else lo = i + 1;
        }
        return k;
    }
}

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 Java-specific trap

If you generalise to T[] with a Comparator, the reflexive shortcut (a, b) -> a - b overflows for large or negative ints, so comparison stops being transitive. The nasty part is WHERE it surfaces: your five-element group sorts will never report it, because Arrays.sort(T[], cmp) runs a plain binary insertion sort below TimSort's MIN_MERGE of 32, and the 'Comparison method violates its general contract!' IllegalArgumentException is thrown only from the merge path. Measured on JDK 17 with an intransitive comparator: 0 throws in 220,000 five-element sorts, first throw at length 32. So the groups sort silently wrong, and the exception ambushes you later from some unrelated 32+ element Arrays.sort or Collections.sort. Use Integer.compare(a, b). The sibling trap: Integer caches -128..127, so an == identity check on the pivot object works for small values and silently fails above 127.

Performance in Java, beyond the O(n)

Integer[] costs a pointer dereference plus a 16-byte header per element and destroys cache locality; int[] keeps the partition scan streaming. The JIT needs roughly 10k loop iterations before C2 compiles the partition, so an unwarmed microbenchmark shows BFPRT losing to Arrays.sort -- measure with JMH and a warmup phase or the numbers are noise. Bounds checks in the scan are usually eliminated once the loop bound is provably a.length. A Comparator call site that sees three or more implementations goes megamorphic and stops inlining, which roughly doubles the per-compare cost. 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 Java, 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 Java, demonstrate proficiency with generics and streams API to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Java code that is both correct and maintainable.

Frequently Asked Questions

Which Java type or library should I use for Median of Medians?

java.util has no selection method. Arrays.sort(int[]) is a dual-pivot quicksort over primitives (modern JDKs add a heapsort fallback so a killer input degrades to n log n instead of quadratic); Arrays.sort(T[], Comparator) is TimSort. PriorityQueue<E> handles small k in O(n log k). IntStream.of(a).sorted() stays primitive -- it buffers into an int[] and calls Arrays.sort -- so the cost is a full copy of the array plus per-element pipeline dispatch, not boxing; you pay boxing only when you cross to Stream<Integer> (.boxed(), or a List<Integer> source), and either way it is an O(n log n) sort where you wanted an O(n) selection. So BFPRT is hand-written, over int[] or long[] with an explicit (lo, hi) range, exactly the way Arrays' own private helpers are shaped.

What is the most common Java mistake when implementing Median of Medians?

If you generalise to T[] with a Comparator, the reflexive shortcut (a, b) -> a - b overflows for large or negative ints, so comparison stops being transitive. The nasty part is WHERE it surfaces: your five-element group sorts will never report it, because Arrays.sort(T[], cmp) runs a plain binary insertion sort below TimSort's MIN_MERGE of 32, and the 'Comparison method violates its general contract!' IllegalArgumentException is thrown only from the merge path. Measured on JDK 17 with an intransitive comparator: 0 throws in 220,000 five-element sorts, first throw at length 32. So the groups sort silently wrong, and the exception ambushes you later from some unrelated 32+ element Arrays.sort or Collections.sort. Use Integer.compare(a, b). The sibling trap: Integer caches -128..127, so an == identity check on the pivot object works for small values and silently fails above 127.

How does Median of Medians actually perform in Java?

Integer[] costs a pointer dereference plus a 16-byte header per element and destroys cache locality; int[] keeps the partition scan streaming. The JIT needs roughly 10k loop iterations before C2 compiles the partition, so an unwarmed microbenchmark shows BFPRT losing to Arrays.sort -- measure with JMH and a warmup phase or the numbers are noise. Bounds checks in the scan are usually eliminated once the loop bound is provably a.length. A Comparator call site that sees three or more implementations goes megamorphic and stops inlining, which roughly doubles the per-compare cost. 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

Before paying full price for a tool, check the student deals on AI and developer tools listed on Noizz.

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.