-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFractional_Knapsack.c
50 lines (44 loc) · 1.23 KB
/
Fractional_Knapsack.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include<stdio.h>
void frac(int p[] , int w[] , int cap , int n);
int main() {
int n;
int p[] = {24, 15, 25};
int w[] = {15, 10, 18};
int cap = 20;
n = sizeof(p) / sizeof(p[0]);
frac(p , w, cap , n);
return 0;
}
void frac(int p[], int w[], int cap, int n) {
float pw[n], tempratio;
int i, j, temprofit, tempweight;
float totalprofit = 0;
for(i = 0; i < n; i++) {
pw[i] = (float)p[i] / w[i];
}
for(i = 0; i <= n - 1; i++) {
for(j = 0; j < n - 1 - i; j++) {
if(pw[j] < pw[j + 1]) {
tempratio = pw[j];
pw[j] = pw[j + 1];
pw[j + 1] = tempratio;
temprofit = p[j];
p[j] = p[j + 1];
p[j + 1] = temprofit;
tempweight = w[j];
w[j] = w[j + 1];
w[j + 1] = tempweight;
}
}
}
for(i = 0; i < n; i++) {
if(cap > w[i]) {
cap = cap - w[i];
totalprofit = totalprofit + p[i];
} else {
totalprofit = totalprofit + (cap * pw[i]);
break;
}
}
printf("The total profit is %.2f", totalprofit);
}