Fractional Knapsack Implementation in Rust
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 Rust as in every other language.
- ✓f64 implements PartialOrd but not Ord - there is no total order over floats once NaN is possible, so the two sort methods on a slice, sort_by and sort_unstable_by, both need a closure that produces an Ordering, and std::cmp::Ordering plus f64::total_cmp (stable since 1.62) are what supply it.
- ✓Reach for sort_unstable_by unless ties specifically need to keep their original relative order - nothing about fractional knapsack does, since only the split item at the boundary matters, not its position among equal-ratio peers.
- ✓The Rust trap: b.ratio().partial_cmp(&a.ratio()).unwrap() panics the instant a comparison returns None, which happens whenever either ratio is NaN - a zero-weight, zero-value item produces exactly that (0.0 / 0.0).
- ✓sort_unstable_by is pattern-defeating quicksort: in-place, O(log n) recursion stack, O(n log n) worst case guaranteed by falling back toward heapsort on adversarial input, and it allocates nothing on the heap.
What Fractional Knapsack actually is
Fractional Knapsack in Rust: what you actually reach for
Rust implementation
struct Item {
name: &'static str,
weight: f64,
value: f64,
}
impl Item {
fn ratio(&self) -> f64 {
self.value / self.weight
}
}
fn fractional_knapsack(items: &mut [Item], capacity: f64) -> f64 {
// sort_unstable_by: in-place pdqsort, O(log n) stack, no heap allocation.
// total_cmp gives a total order over ALL f64 bit patterns, including NaN,
// so it never panics the way partial_cmp(...).unwrap() would on 0.0/0.0
items.sort_unstable_by(|a, b| b.ratio().total_cmp(&a.ratio()));
let mut total_value = 0.0;
let mut remaining = capacity;
for item in items.iter() {
if remaining <= 0.0 {
break;
}
if item.weight <= remaining {
total_value += item.value;
remaining -= item.weight;
} else {
total_value += item.ratio() * remaining;
remaining = 0.0;
}
}
total_value
}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 Rust-specific trap
Performance in Rust, beyond the O(n log n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Rust type or library should I use for Fractional Knapsack?
f64 implements PartialOrd but not Ord - there is no total order over floats once NaN is possible, so the two sort methods on a slice, sort_by and sort_unstable_by, both need a closure that produces an Ordering, and std::cmp::Ordering plus f64::total_cmp (stable since 1.62) are what supply it. Vec<Item> and a plain iter().map(...).sum() finish the rest.
What is the most common Rust mistake when implementing Fractional Knapsack?
b.ratio().partial_cmp(&a.ratio()).unwrap() panics the instant a comparison returns None, which happens whenever either ratio is NaN - a zero-weight, zero-value item produces exactly that (0.0 / 0.0). total_cmp never panics because it defines a total order over every f64 bit pattern including NaN and the signed zeros, at the cost of that order not being mathematically meaningful for NaN - it is a well-defined answer, not a right one.
How does Fractional Knapsack actually perform in Rust?
sort_unstable_by is pattern-defeating quicksort: in-place, O(log n) recursion stack, O(n log n) worst case guaranteed by falling back toward heapsort on adversarial input, and it allocates nothing on the heap. sort_by is the stable choice and needs up to O(n) auxiliary allocation for its adaptive merge - for this algorithm, where stability buys nothing, sort_unstable_by is both faster and the one that actually matches the page's O(1) auxiliary-space claim. Time complexity is O(n log n) and space is O(1).
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.