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

Fractional Knapsack Implementation in Swift

14 min readintermediate
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

  • ✓Fractional Knapsack runs in O(n log n) time and O(1) space, in Swift as in every other language.
  • ✓Sequence.sorted(by:) returns a new, sorted Array from any sequence; MutableCollection.sort(by:) does the same work in place on a var.
  • ✓Use sorted(by:) on a let items: [Item] rather than making it a var just to call sort(by:) - value semantics mean the immutable version costs nothing extra beyond the sort itself, and keeping the input let documents that the function never mutates the caller's array.
  • ✓The Swift trap: The predicate passed to sorted(by:) is documented to require a strict weak ordering, and the Swift standard library states plainly that violating that contract makes the sort's result undefined.
  • ✓Swift's standard sort is an adaptive algorithm guaranteed O(n log n) in the worst case; whole-module optimization lets the compiler specialize a concrete-typed comparator closure and inline it directly into the sort's comparison step, so within one module sorting [Item] by a closure is close to the cost of sorting raw doubles.

What Fractional Knapsack actually is

Fractional knapsack asks for the most value you can pack into a container of fixed capacity when items can be split - take any fraction of an item and get that same fraction of its value. That one difference from the 0/1 version is what makes a greedy strategy provably optimal instead of merely a heuristic: sort every item by value-per-unit-weight, take the highest-ratio items whole for as long as they fit, and take exactly the fraction of the first item that no longer fits needed to use up the remaining capacity. Every language below implements that same four-step algorithm - compute a ratio, sort descending by it, walk the sorted list, stop - and the fill loop itself never needs more than a running total and a remaining-capacity counter, which is the entire O(1) space claim. What is not identical is the sort each language reaches for to get the O(n log n) ordering that dominates the running time. A ratio is a division, and division by a zero-weight item is where the languages split hardest: one of them raises, the rest follow IEEE-754 and produce infinity, and a NaN ratio from a zero-weight, zero-value item breaks whatever ordering contract the sort function documents - sometimes loudly, sometimes not at all. Stability also isn't free everywhere: several of the fastest sort routines below explicitly do not guarantee it, which changes which item ends up split when two items tie on ratio.

Fractional Knapsack in Swift: what you actually reach for

Sequence.sorted(by:) returns a new, sorted Array from any sequence; MutableCollection.sort(by:) does the same work in place on a var. Since Swift 5 both are guaranteed stable - a change from Swift 4.2 and earlier, where the standard library's sort made no stability promise at all.

Swift implementation

Use sorted(by:) on a let items: [Item] rather than making it a var just to call sort(by:) - value semantics mean the immutable version costs nothing extra beyond the sort itself, and keeping the input let documents that the function never mutates the caller's array. Compute ratio as a computed property, var ratio: Double { value / weight }, so it can't silently go stale relative to weight and value.
swift
struct Item {
    let name: String
    let weight: Double
    let value: Double
    var ratio: Double { value / weight }
}

func fractionalKnapsack(_ items: [Item], capacity: Double) -> Double {
    // sorted(by:) since Swift 5 is guaranteed stable; the predicate must be a
    // strict weak ordering - a NaN ratio (zero-weight, zero-value item) breaks
    // that contract and the documented result is undefined
    let byRatio = items.sorted { $0.ratio > $1.ratio }

    var totalValue = 0.0
    var remaining = capacity

    for item in byRatio {
        guard remaining > 0 else { break }
        if item.weight <= remaining {
            totalValue += item.value
            remaining -= item.weight
        } else {
            totalValue += item.ratio * remaining
            remaining = 0
        }
    }
    return totalValue
}

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

The predicate passed to sorted(by:) is documented to require a strict weak ordering, and the Swift standard library states plainly that violating that contract makes the sort's result undefined. A ratio of 0.0 / 0.0 - a zero-weight, zero-value item - is NaN, and every comparison against NaN returns false, which is exactly the kind of inconsistent ordering the contract forbids; the fix is to special-case zero-weight items before they ever reach the comparator.

Performance in Swift, beyond the O(n log n)

Swift's standard sort is an adaptive algorithm guaranteed O(n log n) in the worst case; whole-module optimization lets the compiler specialize a concrete-typed comparator closure and inline it directly into the sort's comparison step, so within one module sorting [Item] by a closure is close to the cost of sorting raw doubles. Across a module boundary, without the closure marked @inlinable, the call goes through a slower, un-inlined path. The asymptotic cost is the same in every language, O(n log n) time and O(1) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Fractional Knapsack between languages.

Real-World Applications

Fractional Knapsack 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 Fractional Knapsack helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Fractional Knapsack appears frequently in onsite coding rounds at mid-to-large tech companies. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Fractional Knapsack 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 Fractional Knapsack 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 Fractional Knapsack?

Sequence.sorted(by:) returns a new, sorted Array from any sequence; MutableCollection.sort(by:) does the same work in place on a var. Since Swift 5 both are guaranteed stable - a change from Swift 4.2 and earlier, where the standard library's sort made no stability promise at all.

What is the most common Swift mistake when implementing Fractional Knapsack?

The predicate passed to sorted(by:) is documented to require a strict weak ordering, and the Swift standard library states plainly that violating that contract makes the sort's result undefined. A ratio of 0.0 / 0.0 - a zero-weight, zero-value item - is NaN, and every comparison against NaN returns false, which is exactly the kind of inconsistent ordering the contract forbids; the fix is to special-case zero-weight items before they ever reach the comparator.

How does Fractional Knapsack actually perform in Swift?

Swift's standard sort is an adaptive algorithm guaranteed O(n log n) in the worst case; whole-module optimization lets the compiler specialize a concrete-typed comparator closure and inline it directly into the sort's comparison step, so within one module sorting [Item] by a closure is close to the cost of sorting raw doubles. Across a module boundary, without the closure marked @inlinable, the call goes through a slower, un-inlined path. Time complexity is O(n log n) and space is O(1).

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 for Devin, check its student and free-tier options 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.