9float profitPerUnit(
Item x) {
return (
float)x.profit / (float)x.weight; }
11int partition(
Item arr[],
int low,
int high) {
12 Item pivot = arr[high];
15 for (
int j = low; j < high; j++) {
18 if (profitPerUnit(arr[j]) <= profitPerUnit(pivot)) {
25 Item temp = arr[i + 1];
26 arr[i + 1] = arr[high];
31void quickSort(
Item arr[],
int low,
int high) {
33 int p = partition(arr, low, high);
35 quickSort(arr, low, p - 1);
36 quickSort(arr, p + 1, high);
41 cout <<
"\nEnter the capacity of the knapsack : ";
44 cout <<
"\n Enter the number of Items : ";
48 for (
int i = 0; i < n; i++) {
49 cout <<
"\nEnter the weight and profit of item " << i + 1 <<
" : ";
50 cin >> itemArray[i].weight;
51 cin >> itemArray[i].profit;
54 quickSort(itemArray, 0, n - 1);
60 while (capacity > 0 && --i >= 0) {
61 if (capacity >= itemArray[i].weight) {
62 maxProfit += itemArray[i].profit;
63 capacity -= itemArray[i].weight;
64 cout <<
"\n\t" << itemArray[i].weight <<
"\t"
65 << itemArray[i].profit;
67 maxProfit += profitPerUnit(itemArray[i]) * capacity;
68 cout <<
"\n\t" << capacity <<
"\t"
69 << profitPerUnit(itemArray[i]) * capacity;
75 cout <<
"\nMax Profit : " << maxProfit;