Memory Alloc
Memory Alloc
#include<stdio.h>
void bestfit(int a[],int b[]);
void worstfit(int a[],int b[]);
void firstfit(int a[],int b[]);
int min(int s[]);
int max(int s[]);
int n,m;
void main()
{
printf("Enter the size of block:");
scanf("%d",&n);
printf("Enter the size to enter in block:");
scanf("%d",&m);
int a[n],b[m];
printf("Enter the size of each block:");
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the size to enter in each block:");
for(int i=0;i<m;i++)
scanf("%d",&b[i]);
firstfit(a,b);
bestfit(a,b);
worstfit(a,b);
}
void firstfit(int a[],int b[])
{
int final[n];
for(int i=0;i<n;i++)
final[i]=-1;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if((a[j]>=b[i]) && final[j]==-1)
{
final[j]=b[i];
break;
}
}
}
printf("\nFirst Fit:\n");
for(int i=0;i<n;i++)
{
printf("%d is stored in %d block\n",final[i],a[i]);
}
}
void bestfit(int a[],int b[])
{
int final[n],sub[n],t,ind;
for(int i=0;i<n;i++)
final[i]=-1;
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
sub[j]=999;
if((a[j]>=b[i]) && final[j]==-1)
{
t=a[j]-b[i];
if(t<sub[j])
sub[j]=t;
}
}
ind=min(sub);
final[ind]=b[i];
}
printf("\nBest Fit:\n");
for(int i=0;i<n;i++)
{
printf("%d is stored in %d block\n",final[i],a[i]);
}
}
void worstfit(int a[],int b[])
{
int final[n],sub[n],t,ind;
for(int i=0;i<n;i++)
final[i]=-1;
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
sub[j]=-999;
if((a[j]>=b[i]) && final[j]==-1)
{
t=a[j]-b[i];
if(t>sub[j])
sub[j]=t;
}
}
ind=max(sub);
final[ind]=b[i];
}
printf("\nWorst Fit:\n");
for(int i=0;i<n;i++)
{
printf("%d is stored in %d block\n",final[i],a[i]);
}
}
int min(int s[])
{
int m,x=0;
m=s[0];
for(int i=1;i<n;i++)
{
if(s[i]<m)
{
m=s[i];
x=i;
}
}
return x;
}
int max(int s[])
{
int m,x=0;
m=s[0];
for(int i=1;i<n;i++)
{
if(s[i]>m)
{
m=s[i];
x=i;
}
}
return x;
}
Output:
Enter the size of block:5
Enter the size to enter in block:4
Enter the size of each block:500
100
300
200
600
Enter the size to enter in each block:212
417
112
426
First Fit:
212 is stored in 500 block
-1 is stored in 100 block
112 is stored in 300 block
-1 is stored in 200 block
417 is stored in 600 block
Best Fit:
417 is stored in 500 block
-1 is stored in 100 block
212 is stored in 300 block
112 is stored in 200 block
426 is stored in 600 block
Worst Fit:
426 is stored in 500 block
-1 is stored in 100 block
112 is stored in 300 block
-1 is stored in 200 block
212 is stored in 600 block