algorithmbinary-searchknapsack-problem

Solving the Fractional Knapsack problem using Binary Search


The Fractional Knapsack Problem revolves around selecting items from a given set to fit into a knapsack of limited capacity. Each item has a weight and a value associated with it, and the goal is to select items to maximize the total value within the capacity constraint.

In the Fractional Knapsack Problem, unlike the 0/1 Knapsack Problem, we are allowed to take fractions of items, enabling us to achieve a better overall value. This makes the Fractional Knapsack Problem more flexible and practical for real-world scenarios.

Can the Fractional Knapsack Problem be solved using Binary Search?


Solution

  • TL;DR Technically, you can't technically solve this problem with the standard binary search algorithm. You could, however, solve it with a modified version of the binary search algorithm, although the modified algorithm would be asymptotically worse than just iterating through the sorted array (i.e. O(nlogn) vs. O(n), respectively).

    I'm not going to write out the standard algorithm itself, but the binary search algorithm "finds the position of a target value within a sorted array". Therefore, you can't use the standard binary search algorithm in the fractional knapsack problem because you don't know the "target value" (i.e. weight) of the next item you're trying to find, unless you go the index of the element in the array that you're trying to find, at which time you're already there, so there's no need to use binary search.

    So effectively, if you choose to use binary search for this problem, what you're really saying is that you're using to use a binary search algorithm to get to the next adjacent spot in the sorted array instead of just incrementing the position you're already at in the array by 1.

    Now, you could technically use a different version of binary search by changing the condition to test for. In the standard binary search algorithm, your test is the value of the item you're looking for. You don't have that in your problem. Instead, what you have is the value of the element that is greater than (or possibly equal to if there are duplicate item weights) this element. Thus, if you use binary search, you need to change your test condition so that you're always checking the value of the element to either the left or the right of your current position. As such, it can be done, but it's impractical.