Median of Medians Implementation in Swift
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 Swift as in every other language.
- ✓No nth-element in the standard library. MutableCollection.partition(by:) is real and returns the index of the first element of the second partition -- the exact primitive the quickselect layer needs.
- ✓Write against MutableCollection & RandomAccessCollection and move with index(_:offsetBy:) rather than assuming Int indices -- assuming 0..<count is the review comment on any generic algorithm.
- ✓The Swift trap: Copy-on-write costs you a full O(n) buffer copy the first time you mutate while a second reference exists -- a let snapshot for a debug print, the array captured by a closure, an element stashed in a struct passed alongside.
- ✓Generic code compiled across a module boundary goes through the value witness table and a protocol-witness call per comparison unless the specialiser can see the body -- so a package-level select<T: Comparable> pays a dynamic call per compare until you add @inlinable or build with whole-module optimization.
What Median of Medians actually is
Median of Medians in Swift: what you actually reach for
Swift implementation
func ins<T: Comparable>(_ a: inout [T], _ lo: Int, _ hi: Int) {
var i = lo + 1
while i < hi {
let v = a[i]
var j = i - 1
while j >= lo && a[j] > v {
a[j + 1] = a[j]
j -= 1
}
a[j + 1] = v
i += 1
}
}
func pivotIndex<T: Comparable>(_ a: inout [T], _ lo: Int, _ hi: Int) -> Int {
let n = hi - lo
if n <= 5 {
ins(&a, lo, hi)
return lo + n / 2
}
var m = lo
var g = lo
while g < hi {
let e = Swift.min(g + 5, hi)
ins(&a, g, e)
a.swapAt(m, g + (e - g) / 2)
m += 1
g += 5
}
return selectNth(&a, lo, m, lo + (m - lo) / 2)
}
/// Reorders a[lo..<hi] so a[k] is the k-th smallest; returns k.
@discardableResult
func selectNth<T: Comparable>(_ a: inout [T], _ lo0: Int, _ hi0: Int, _ k: Int) -> Int {
var lo = lo0, hi = hi0
while hi - lo > 1 {
let p = pivotIndex(&a, lo, hi)
a.swapAt(lo, p)
let pv = a[lo]
var i = lo
for j in (lo + 1)..<hi where a[j] < pv {
i += 1
a.swapAt(i, j)
}
a.swapAt(lo, i)
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 FreeThe Swift-specific trap
Performance in Swift, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Swift type or library should I use for Median of Medians?
No nth-element in the standard library. MutableCollection.partition(by:) is real and returns the index of the first element of the second partition -- the exact primitive the quickselect layer needs. sorted() / sort() are a modified timsort since Swift 5 (an adaptive merge sort that exploits existing runs; the API still does not promise stability, though the implementation is stable in practice). The swift-algorithms package (import Algorithms) adds min(count:) and max(count:) for small k and partitioningIndex(where:) for a sorted-predicate split, but it does not ship a deterministic selection, so BFPRT is yours to write. withUnsafeMutableBufferPointer is the escape hatch when the generic layer costs too much.
What is the most common Swift mistake when implementing Median of Medians?
Copy-on-write costs you a full O(n) buffer copy the first time you mutate while a second reference exists -- a let snapshot for a debug print, the array captured by a closure, an element stashed in a struct passed alongside. That is a one-off, not a per-level tax: after the copy your buffer is uniquely referenced again (measured, one held reference produces exactly one copy across ten successive mutations), so the algorithm stays linear with an additive O(n) on top. It turns genuinely quadratic only when each recursion level manufactures a FRESH extra reference -- a closure capturing the array per call, or a logging helper taking [T] by value inside the loop. Passing inout, as below, keeps uniqueness throughout. The other Swift-only trap is exclusivity: swap(&a[i], &a[j]) takes two overlapping inout accesses to the same array and swiftc rejects it at compile time -- 'error: overlapping accesses to a, but modification requires exclusive access; consider calling MutableCollection.swapAt(_:_:)' -- which is exactly why swapAt(_:_:) exists. Dynamic enforcement gives you the runtime 'Simultaneous accesses' trap instead when the conflict runs through a class property or a global rather than a local. Plain element assignment such as a[j + 1] = a[j] under inout is a read then a write, never overlapping, and is always fine.
How does Median of Medians actually perform in Swift?
Generic code compiled across a module boundary goes through the value witness table and a protocol-witness call per comparison unless the specialiser can see the body -- so a package-level select<T: Comparable> pays a dynamic call per compare until you add @inlinable or build with whole-module optimization. If Element is a class, every swap issues retain/release pairs; ARC traffic on a linear scan of a million elements is measurable. withUnsafeMutableBufferPointer strips both the bounds check and the uniqueness check from the inner loop and is the standard way to recover C-level constants. Time complexity is O(n) and space is O(n).
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? Devin 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.