Fractional Knapsack Implementation in C#
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 C# as in every other language.
- ✓System.Array.Sort<T> and List<T>.Sort both sort in place using an introspective sort - a quicksort/heapsort/insertion-sort hybrid.
- ✓Reach for OrderByDescending(it => it.Ratio) when readability and stable tie-breaking matter more than the last bit of throughput - it reads as a direct statement of intent and composes cleanly with Where or Take if the caller later needs to filter items first.
- ✓The C# trap: Array.Sort's introspective sort makes no stability guarantee, and its documentation says so directly - two items tied on ratio can end up in either order, and that order is not guaranteed to be consistent between calls or .NET versions.
- ✓OrderByDescending is deferred: nothing runs until the sequence is enumerated, and ToArray() or a foreach forces it, at which point LINQ buffers the whole sequence and runs a stable sort over it - an O(n) allocation on top of the O(n log n) comparisons.
What Fractional Knapsack actually is
Fractional Knapsack in C#: what you actually reach for
C# implementation
using System;
using System.Linq;
public record Item(string Name, double Weight, double Value)
{
public double Ratio => Value / Weight;
}
public static class Knapsack
{
public static double FractionalKnapsack(Item[] items, double capacity)
{
// Array.Sort is introspective sort: in-place, O(log n) stack, but NOT
// stable. Enumerable.OrderByDescending IS documented as stable, at the
// cost of an O(n) buffering allocation - pick based on which you need.
var byRatio = items.OrderByDescending(it => it.Ratio).ToArray();
double totalValue = 0.0;
double remaining = capacity;
foreach (var item in byRatio)
{
if (remaining <= 0) 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 C#-specific trap
Performance in C#, beyond the O(n log n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which C# type or library should I use for Fractional Knapsack?
System.Array.Sort<T> and List<T>.Sort both sort in place using an introspective sort - a quicksort/heapsort/insertion-sort hybrid. System.Linq.Enumerable.OrderByDescending does the equivalent job lazily and is documented to perform a stable sort, at the cost of buffering into a new sequence rather than sorting the caller's array in place.
What is the most common C# mistake when implementing Fractional Knapsack?
Array.Sort's introspective sort makes no stability guarantee, and its documentation says so directly - two items tied on ratio can end up in either order, and that order is not guaranteed to be consistent between calls or .NET versions. Code that silently assumed Array.Sort behaves like OrderBy (stable) will pass every test where ratios happen to be distinct and then produce a different split item the day two items in real data tie.
How does Fractional Knapsack actually perform in C#?
OrderByDescending is deferred: nothing runs until the sequence is enumerated, and ToArray() or a foreach forces it, at which point LINQ buffers the whole sequence and runs a stable sort over it - an O(n) allocation on top of the O(n log n) comparisons. Array.Sort sorts the array you already have, in place, with no LINQ enumerator boxing and no extra buffer beyond the introspective sort's own O(log n) recursion stack. 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 trialStudying for this? Student discounts on developer tools are collected on Noizz, tool by tool.
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.