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

Median of Medians Implementation in JavaScript

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 JavaScript as in every other language.
  • ✓Nothing in the language does selection. Array.prototype.sort with a comparator is your only built-in ordering primitive, and TypedArray.prototype.sort (Float64Array, Int32Array) sorts numerically by default instead of by string.
  • ✓A reviewer will not accept arr.sort() on numbers without a comparator, and will not accept slice() inside the recursion -- pass lo/hi indices into one buffer.
  • ✓The JavaScript trap: Array.prototype.sort() with no comparator sorts by STRING: [10, 9, 100] becomes [10, 100, 9].
  • ✓V8 element kinds decide the constant factor. A holey array from new Array(n) forces every load down the HOLEY_ELEMENTS path, which must consult the prototype chain in case the hole is inherited; a packed Float64Array stores raw doubles and lets TurboFan keep swaps in registers with no boxing.

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

Nothing in the language does selection. Array.prototype.sort with a comparator is your only built-in ordering primitive, and TypedArray.prototype.sort (Float64Array, Int32Array) sorts numerically by default instead of by string. The ecosystem standard is the quickselect package (also re-exported as d3.quickselect from d3-array), which implements Floyd-Rivest, not BFPRT: it is faster in practice but only probabilistically bounded. If you need the deterministic worst case, you write the five-group recursion by hand over a Float64Array.

JavaScript implementation

A reviewer will not accept arr.sort() on numbers without a comparator, and will not accept slice() inside the recursion -- pass lo/hi indices into one buffer. They expect Float64Array or Int32Array for numeric selection so element access is monomorphic, |0 or >> 1 for the midpoint instead of Math.floor, and the outer quickselect as a for(;;) loop that narrows lo/hi. Exporting a k-th value while also mutating the caller's array must be documented in the JSDoc; silent in-place reorder gets flagged.
javascript
function ins(a, lo, hi) {
  for (let i = lo + 1; i < hi; i++) {
    const v = a[i];
    let j = i - 1;
    while (j >= lo && a[j] > v) { a[j + 1] = a[j]; j--; }
    a[j + 1] = v;
  }
}

function pivot(a, lo, hi) {
  const n = hi - lo;
  if (n <= 5) { ins(a, lo, hi); return lo + (n >> 1); }
  let m = lo;
  for (let g = lo; g < hi; g += 5) {
    const e = Math.min(g + 5, hi);
    ins(a, g, e);
    const mid = g + ((e - g) >> 1);
    const t = a[m]; a[m] = a[mid]; a[mid] = t;
    m++;
  }
  return select(a, lo, m, lo + ((m - lo) >> 1));
}

function select(a, lo, hi, k) {
  for (;;) {
    if (hi - lo <= 1) return k;
    const p = pivot(a, lo, hi);
    let t = a[lo]; a[lo] = a[p]; a[p] = t;
    const pv = a[lo];
    let i = lo;
    for (let 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;
  }
}

const buf = Float64Array.from([9, 3, 7, 1, 8, 2, 5]);
const med = buf[select(buf, 0, buf.length, buf.length >> 1)];

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

Array.prototype.sort() with no comparator sorts by STRING: [10, 9, 100] becomes [10, 100, 9]. Sort your five-element groups that way and every group median is wrong -- yet the algorithm still returns the correct k-th element, because a bad pivot only costs balance, never correctness. You get a silent, untestable loss of the linear worst case that unit tests pass. The second trap is the Float64Array boundary itself: writing a NaN, a string or undefined into one never throws, because the typed array coerces -- buf[i] = 'abc' silently stores NaN, buf[i] = 1e400 stores Infinity. Verified on the code below: one NaN in [5, 3, NaN, 1, 9, 2, 7] makes select(k=3) return 3 instead of 5, in 0 ms and with no error, because the bounded scan simply never counts NaN as less than the pivot. Validate with Number.isFinite at the boundary before you fill the buffer -- the typed array will not do it for you.

Performance in JavaScript, beyond the O(n)

V8 element kinds decide the constant factor. A holey array from new Array(n) forces every load down the HOLEY_ELEMENTS path, which must consult the prototype chain in case the hole is inherited; a packed Float64Array stores raw doubles and lets TurboFan keep swaps in registers with no boxing. A comparator closure is inlined while the call site stays monomorphic; feeding the same select() more than about four distinct comparator shapes turns that site megamorphic, and it stops inlining there for every caller from then on. The group-of-five insertion sort should be inlined rather than delegated to sort(), which allocates and enters the comparator ABI n/5 times. 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 JavaScript, 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 JavaScript, demonstrate proficiency with closures and async/await to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic JavaScript code that is both correct and maintainable.

Frequently Asked Questions

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

Nothing in the language does selection. Array.prototype.sort with a comparator is your only built-in ordering primitive, and TypedArray.prototype.sort (Float64Array, Int32Array) sorts numerically by default instead of by string. The ecosystem standard is the quickselect package (also re-exported as d3.quickselect from d3-array), which implements Floyd-Rivest, not BFPRT: it is faster in practice but only probabilistically bounded. If you need the deterministic worst case, you write the five-group recursion by hand over a Float64Array.

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

Array.prototype.sort() with no comparator sorts by STRING: [10, 9, 100] becomes [10, 100, 9]. Sort your five-element groups that way and every group median is wrong -- yet the algorithm still returns the correct k-th element, because a bad pivot only costs balance, never correctness. You get a silent, untestable loss of the linear worst case that unit tests pass. The second trap is the Float64Array boundary itself: writing a NaN, a string or undefined into one never throws, because the typed array coerces -- buf[i] = 'abc' silently stores NaN, buf[i] = 1e400 stores Infinity. Verified on the code below: one NaN in [5, 3, NaN, 1, 9, 2, 7] makes select(k=3) return 3 instead of 5, in 0 ms and with no error, because the bounded scan simply never counts NaN as less than the pivot. Validate with Number.isFinite at the boundary before you fill the buffer -- the typed array will not do it for you.

How does Median of Medians actually perform in JavaScript?

V8 element kinds decide the constant factor. A holey array from new Array(n) forces every load down the HOLEY_ELEMENTS path, which must consult the prototype chain in case the hole is inherited; a packed Float64Array stores raw doubles and lets TurboFan keep swaps in registers with no boxing. A comparator closure is inlined while the call site stays monomorphic; feeding the same select() more than about four distinct comparator shapes turns that site megamorphic, and it stops inlining there for every caller from then on. The group-of-five insertion sort should be inlined rather than delegated to sort(), which allocates and enters the comparator ABI n/5 times. 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? Replit free tiers and academic plans are laid out 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.