profitPerUnit(
Itemx) {
return(
float)x.profit / (float)x.weight; }
11intpartition(
Itemarr[],
intlow,
inthigh) {
12 Itempivot = arr[high];
15 for(
intj = low; j < high; j++) {
18 if(profitPerUnit(arr[j]) <= profitPerUnit(pivot)) {
25 Itemtemp = arr[i + 1];
26arr[i + 1] = arr[high];
31voidquickSort(
Itemarr[],
intlow,
inthigh) {
33 intp = partition(arr, low, high);
35quickSort(arr, low, p - 1);
36quickSort(arr, p + 1, high);
41cout <<
"\nEnter the capacity of the knapsack : ";
44cout <<
"\n Enter the number of Items : ";
48 for(
inti = 0; i < n; i++) {
49cout <<
"\nEnter the weight and profit of item "<< i + 1 <<
" : ";
50cin >> itemArray[i].weight;
51cin >> itemArray[i].profit;
54quickSort(itemArray, 0, n - 1);
60 while(capacity > 0 && --i >= 0) {
61 if(capacity >= itemArray[i].weight) {
62maxProfit += itemArray[i].profit;
63capacity -= itemArray[i].weight;
64cout <<
"\n\t"<< itemArray[i].weight <<
"\t" 65<< itemArray[i].profit;
67maxProfit += profitPerUnit(itemArray[i]) * capacity;
68cout <<
"\n\t"<< capacity <<
"\t" 69<< profitPerUnit(itemArray[i]) * capacity;
75cout <<
"\nMax Profit : "<< maxProfit;
int main()
Main function.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4