Skip to content

Commented the algorithm logic #2957

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 12 additions & 5 deletions greedy_algorithms/knapsack.cpp
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
#include <iostream>
using namespace std;

struct Item {
struct Item {
int weight;
int profit;
};

float profitPerUnit(Item x) { return (float)x.profit / (float)x.weight; }
//function to calculate input data for algo which is profit/wt of each item
float profitPerUnit(Item x) { return (float)x.profit / (float)x.weight; }

int partition(Item arr[], int low, int high) {
Item pivot = arr[high]; // pivot
Expand Down Expand Up @@ -39,32 +40,38 @@ void quickSort(Item arr[], int low, int high) {

int main() {
cout << "\nEnter the capacity of the knapsack : ";
float capacity;
float capacity; //constraint
cin >> capacity;
cout << "\n Enter the number of Items : ";
int n;
cin >> n;
//create item data structure, array here of size n
Item *itemArray = new Item[n];
for (int i = 0; i < n; i++) {
cout << "\nEnter the weight and profit of item " << i + 1 << " : ";
cin >> itemArray[i].weight;
cin >> itemArray[i].profit;
}

quickSort(itemArray, 0, n - 1);
quickSort(itemArray, 0, n - 1); // sorts by profitperunit parameter in the partition function

// show(itemArray, n);

//Apply algorithm ->
float maxProfit = 0;
int i = n;
while (capacity > 0 && --i >= 0) {
//start from item with largest profitperunit
if (capacity >= itemArray[i].weight) {
//Add to the profit and reduce the capacity
maxProfit += itemArray[i].profit;
capacity -= itemArray[i].weight;
//Print the respective wt taken and profit of that item
cout << "\n\t" << itemArray[i].weight << "\t"
<< itemArray[i].profit;
} else {
// take the fraction of item wt such that capacity is exhausted but not overloaded
maxProfit += profitPerUnit(itemArray[i]) * capacity;
//print the fractional wt taken and profit obtained on this wt of item
cout << "\n\t" << capacity << "\t"
<< profitPerUnit(itemArray[i]) * capacity;
capacity = 0;
Expand Down