Fractional Knapsack Implementation in Java
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 Java as in every other language.
- ✓java.util.function.Comparator with comparingDouble builds a comparator straight from a double-returning method reference, Item::ratio, without boxing the double into a Double the way a hand-written Comparator<Item> is easy to get wrong.
- ✓Declare Item as a record with a ratio() instance method rather than a class with a separately-computed field - a record's canonical constructor and accessor methods make the value-object intent explicit, and ratio() being derived rather than stored means it can never drift out of sync with weight and value.
- ✓The Java trap: A hand-rolled comparator like (a, b) -> (int) (a.ratio() - b.ratio()) truncates a fractional difference to an int, so ratios that differ by less than 1.0 all compare equal even when they aren't - that breaks transitivity, and Arrays.sort's TimSort-based implementation actively checks for this: a broken comparator on a large enough array throws IllegalArgumentException: Comparison method violates its general contract!
- ✓Arrays.sort(Object[]) is TimSort - stable, O(n log n) worst case guaranteed - but it needs an auxiliary array for merging, so it is not in-place the way Arrays.sort(double[]) is; the primitive overload uses a Dual-Pivot Quicksort that sorts in place with O(log n) stack and no comparator call overhead at all, because primitive comparison is a machine instruction rather than a virtual dispatch through Comparator.compare.
What Fractional Knapsack actually is
Fractional Knapsack in Java: what you actually reach for
Java implementation
import java.util.*;
record Item(String name, double weight, double value) {
double ratio() { return value / weight; }
}
public final class Knapsack {
public static double fractionalKnapsack(Item[] items, double capacity) {
Item[] byRatio = items.clone();
// Arrays.sort(Object[]) is TimSort: stable, O(n log n) worst case,
// but throws "Comparison method violates its general contract!" if the
// comparator isn't a real total order - comparingDouble avoids that trap
Arrays.sort(byRatio, Comparator.comparingDouble(Item::ratio).reversed());
double totalValue = 0.0;
double remaining = capacity;
for (Item item : byRatio) {
if (remaining <= 0) break;
if (item.weight() <= remaining) {
totalValue += item.value();
remaining -= item.weight();
} else {
totalValue += item.ratio() * remaining;
remaining = 0.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 Java-specific trap
Performance in Java, beyond the O(n log n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Java type or library should I use for Fractional Knapsack?
java.util.function.Comparator with comparingDouble builds a comparator straight from a double-returning method reference, Item::ratio, without boxing the double into a Double the way a hand-written Comparator<Item> is easy to get wrong. Arrays.sort(T[], Comparator) sorts an object array, and records (Java 16+) give Item its fields, constructor, equals/hashCode, and toString in one declaration.
What is the most common Java mistake when implementing Fractional Knapsack?
A hand-rolled comparator like (a, b) -> (int) (a.ratio() - b.ratio()) truncates a fractional difference to an int, so ratios that differ by less than 1.0 all compare equal even when they aren't - that breaks transitivity, and Arrays.sort's TimSort-based implementation actively checks for this: a broken comparator on a large enough array throws IllegalArgumentException: Comparison method violates its general contract! at sort time rather than quietly returning a wrong order.
How does Fractional Knapsack actually perform in Java?
Arrays.sort(Object[]) is TimSort - stable, O(n log n) worst case guaranteed - but it needs an auxiliary array for merging, so it is not in-place the way Arrays.sort(double[]) is; the primitive overload uses a Dual-Pivot Quicksort that sorts in place with O(log n) stack and no comparator call overhead at all, because primitive comparison is a machine instruction rather than a virtual dispatch through Comparator.compare. 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 trialIf you are a student, see what Replit offers students for free 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.