You are on page 1of 2

Nov 2010

Page |1

Program no-14

Aim-to write a program in c to implement fractional knapsack problem.

SOURCE CODE
#include<stdio.h>
#include<conio.h>
int partition(float P[],float p[],float w[],int s,int r)
{
float x=P[r];
int i,j;
i=s-1;
for(j=s;j<r;j++)
{
if(P[j]>=x)
{
i=i+1;
P[i]=P[i]+P[j]-(P[j]=P[i]);
p[i]=p[i]+p[j]-(p[j]=p[i]);
w[i]=w[i]+w[j]-(w[j]=w[i]);
}
}
P[i+1]=P[i+1]+P[r]-(P[r]=P[i+1]);
p[i+1]=p[i+1]+p[r]-(p[r]=p[i+1]);
w[i+1]=w[i+1]+w[r]-(w[r]=w[i+1]);
return(i+1);
}
void sort(float P[],float p[],float w[],int s,int r)
{
int q;
if(s<r)
{
q=partition(P,p,w,s,r);
sort(P,p,w,s,q-1);
sort(P,p,w,q+1,r);
}
}
void main()
{
float p[20],w[20],x[20],P[20],M,key[3],Result=0;
Nov 2010
Page |2

int i,j,n,s=0;
clrscr();
printf("Enter the number of elements:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the profit & weight of %d element:",i+1);
scanf("%f%f",&p[i],&w[i]);
}
printf("Enter the maximum possible weight:");
scanf("%f",&M);
for(i=0;i<n;i++)
P[i]=p[i]/w[i];
sort(P,p,w,s,n-1);
for(i=0;i<n;i++)
x[i]=0.0;
for(i=0;i<n;i++)
{
if(w[i]>M)
break;
x[i]=1;
M=M-w[i];
}
if(i<n)
x[i]=M/w[i];
for(i=0;i<n;i++)
Result+=p[i]*x[i];
printf("Maximum profit earned is %f",Result);
getch();
}

OUTPUT:
Enter the number of elements:5
Enter the profit & weight of 1 element:30 5
Enter the profit & weight of 2 element:20 10
Enter the profit & weight of 3 element:100 20
Enter the profit & weight of 4 element:90 30
Enter the profit & weight of 5 element:160 40
Enter the maximum possible weight:60
Maximum profit earned is 270.000000

You might also like