Median of Medians Implementation in JavaScript
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 in JavaScript: what you actually reach for
JavaScript implementation
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 FreeThe JavaScript-specific trap
Performance in JavaScript, beyond the O(n)
Real-World Applications
Interview Tips & Practice
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).
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? Replit free tiers and academic plans are laid out on Noizz.
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.