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

Median of Medians Implementation in Swift

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

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.

Swift implementation

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. Take the ordering as areInIncreasingOrder: (Element, Element) -> Bool, matching sort(by:), and document that it must be a strict weak ordering. Use swapAt(_:_:) instead of a manual temp, mark the entry point @inlinable if it ships in a package, and take the buffer inout instead of returning a new array. The snippet below deliberately takes inout [T] with Int indices to keep the algorithm readable; a shipped version should be generic over MutableCollection & RandomAccessCollection with an areInIncreasingOrder parameter.
swift
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 Free

The Swift-specific 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. 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.

Performance in Swift, beyond the O(n)

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. 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 Swift, 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 Swift, demonstrate proficiency with optionals and value types to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Swift code that is both correct and maintainable.

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

Share this article

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

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? Devin 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.