Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

#include<stdio.

h>
int main()
{
float weight[50],profit[50],ratio[50],Totalvalue,temp,capacity,amount;
int count=0;

int i,j,n;
printf("Enter the number of items:");
scanf("%d",&n);

for(i=0;i<n;i++)
{
count++;
printf("Enter the weight and profit for item[%d] :\n",i);
scanf("%f %f",&weight[i],&profit[i]);
}
printf("Enter the capacity of knapsack :\n");
scanf("%f",&capacity);

for(i=0;i<n;i++)
{
count++;
ratio[i]= profit[i]/weight[i];
}
for(i=0;i<n;i++)
{
count++;
for(j=i+1;j<n;j++)
{
count++;
if(ratio[i] <ratio[j])
{
count++;
temp=ratio[j];
ratio[j]=ratio[i];
ratio[i]=temp;

temp=weight[j];
weight[j]=weight[i];
weight[i]=temp;

temp=profit[j];
profit[j]=profit[i];
profit[i]=temp;
}
}
}

printf("knapsack problem using greedy algorithm :\n");


for(i=0;i<n;i++)
{
count++;
if(weight[i] >capacity)
{
count++;
break;
}
else
{
count++;
Totalvalue=Totalvalue+ profit[i];
capacity=capacity-weight[i];
}
}
if(i<n)
Totalvalue=Totalvalue+(ratio[i]*capacity);
printf("The maximum profit value is: %f\n",Totalvalue);

printf("Number of count steps are: %d\n",count);


return 0;
}
/*
ryk@pc216:~/DAA_12$ cc knapsack_algorithm.c
ryk@pc216:~/DAA_12$ ./a.out
Enter the number of items:3
Enter the weight and profit for item[0] :
18
25
Enter the weight and profit for item[1] :
15
24
Enter the weight and profit for item[2] :
10
15
Enter the capacity of knapsack :
20
knapsack problem using greedy algorithm :
The maximum profit value is: 31.500000
------------------------------------------------------------------------
ryk@pc216:~/DAA_12$ cc knapsack_algorithm.c
ryk@pc216:~/DAA_12$ ./a.out
Enter the number of items:4
Enter the weight and profit for item[0] :
3
5
Enter the weight and profit for item[1] :
5
11
Enter the weight and profit for item[2] :
4
6
Enter the weight and profit for item[3] :
8
13
Enter the capacity of knapsack :
11
knapsack problem using greedy algorithm :
The maximum profit value is: 20.875000
Number of count steps are: 27

*/

You might also like