Fractional Knapsack 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
- ✓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 in Swift: what you actually reach for
Swift implementation
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 FreeThe Swift-specific trap
Performance in Swift, beyond the O(n log n)
Real-World Applications
Interview Tips & Practice
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).
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 trialBefore paying for Devin, check its student and free-tier options 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.