package main import "fmt" type Item struct { value float64 weight float64 } func fractionalKnapsack(items []Item, capacity float64) float64 { n := len(items) ratio := make([]float64, n) for i := 0; i < n; i++ { ratio[i] = items[i].value / items[i].weight } // Sort items by ratio descending (simple bubble sort for clarity) for i := 0; i < n-1; i++ { for j := 0; j < n-i-1; j++ { if ratio[j] < ratio[j+1] { ratio[j], ratio[j+1] = ratio[j+1], ratio[j] items[j], items[j+1] = items[j+1], items[j] } } } totalValue := 0.0 for i := 0; i < n; i++ { if capacity == 0 { break } if items[i].weight <= capacity { capacity -= items[i].weight totalValue += items[i].value } else { fraction := capacity / items[i].weight totalValue += items[i].value * fraction capacity = 0 } } return totalValue } func main() { items := []Item{{value: 60, weight: 10}, {value: 100, weight: 20}, {value: 120, weight: 30}} capacity := 50.0 fmt.Printf("%.2f", fractionalKnapsack(items, capacity)) }
The function sorts items by value-to-weight ratio descending. It picks whole items if possible, else a fraction of the last item to fill capacity. The maximum value is 240.00.
Fractional knapsack allows dividing items, so you can take any fraction of an item, gaining proportional value. This is why greedy approach works optimally.
for i := 0; i < n-1; i++ { for j := 0; j < n-i-1; j++ { if ratio[j] > ratio[j+1] { ratio[j], ratio[j+1] = ratio[j+1], ratio[j] items[j], items[j+1] = items[j+1], items[j] } } }
The code sorts ratios ascending because it swaps when ratio[j] > ratio[j+1]. Fractional knapsack requires descending order for correct greedy selection.
package main import "fmt" type Item struct { value float64 weight float64 } func fractionalKnapsack(items []Item, capacity float64) float64 { totalValue := 0.0 for _, item := range items { if capacity == 0 { break } if item.weight <= capacity { capacity -= item.weight totalValue += item.value } else { fraction := capacity / item.weight totalValue += item.value * fraction capacity = 0 } } return totalValue } func main() { items := []Item{{value: 50, weight: 5}, {value: 100, weight: 10}} capacity := 0.0 fmt.Printf("%.2f", fractionalKnapsack(items, capacity)) }
With zero capacity, the function breaks immediately and returns 0.00 value.
The greedy approach works optimally for fractional knapsack because items can be split, so taking the best ratio first maximizes value. For 0/1 knapsack, items are indivisible, so greedy fails.
