最佳适应算法代码
时间: 2023-07-03 07:23:59 浏览: 144
最佳适应算法(Best Fit Algorithm)是一种内存分配算法,用于在内存管理中找到最小可用块来存储作业。以下是使用C语言编写的最佳适应算法代码:
```c
#include<stdio.h>
int main()
{
int memory[10], process[10], allocation[10], flag[10];
int i, j, n, m, min, pos;
printf("Enter the number of memory blocks: ");
scanf("%d", &n);
printf("Enter the size of each memory block:\n");
for(i=0; i<n; i++)
{
scanf("%d", &memory[i]);
}
printf("Enter the number of processes: ");
scanf("%d", &m);
printf("Enter the size of each process:\n");
for(i=0; i<m; i++)
{
scanf("%d", &process[i]);
flag[i] = 0;
}
for(i=0; i<m; i++)
{
min = 9999;
pos = -1;
for(j=0; j<n; j++)
{
if(memory[j]>=process[i] && flag[j]==0)
{
if(memory[j]-process[i]<min)
{
min = memory[j]-process[i];
pos = j;
}
}
}
if(pos != -1)
{
allocation[i] = pos;
flag[pos] = 1;
memory[pos] = memory[pos] - process[i];
}
}
printf("\nProcess No.\tProcess Size\tMemory Block No.\n");
for(i=0; i<m; i++)
{
printf(" %d\t\t %d\t\t ", i+1, process[i]);
if(flag[i]==1)
printf("%d", allocation[i]+1);
else
printf("Not Allocated");
printf("\n");
}
return 0;
}
```
该程序首先要求用户输入内存块和进程的数量及其大小,然后使用最佳适应算法找到最小可用块,并将进程分配给该块。最后,程序输出分配结果表格。
阅读全文