-
Notifications
You must be signed in to change notification settings - Fork 1
/
Best_Fit_Allocation.cpp
83 lines (72 loc) · 1.88 KB
/
Best_Fit_Allocation.cpp
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// C++ implementation of Best - Fit algorithm
#include<bits/stdc++.h>
using namespace std;
// Function to allocate memory to blocks as per Best fit
// algorithm
void bestFit(int *blockSize, int m, int *processSize, int n)
{
// Stores block id of the block allocated to a
// process
int allocation[n];
// Initially no block is assigned to any process
memset(allocation, -1, sizeof(allocation));
// pick each process and find suitable blocks
// according to its size ad assign to it
for (int i=0; i<n; i++)
{
// Find the best fit block for current process
int bestIdx = -1;
for (int j=0; j<m; j++)
{
if (blockSize[j] >= processSize[i])
{
if (bestIdx == -1)
bestIdx = j;
else if (blockSize[bestIdx] > blockSize[j])
bestIdx = j;
}
}
// If we could find a block for current process
if (bestIdx != -1)
{
// allocate block j to p[i] process
allocation[i] = bestIdx;
// Reduce available memory in this block.
blockSize[bestIdx] -= processSize[i];
}
}
cout << "\nProcess No.\tProcess Size\tBlock no.\n";
for (int i = 0; i < n; i++)
{
cout << " " << i+1 << "\t\t" << processSize[i] << "\t\t";
if (allocation[i] != -1)
cout << allocation[i] + 1;
else
cout << "Not Allocated";
cout << endl;
}
}
int main()
{
int p , b , *blockSize , *processSize;
cout<<"\nEnter no. of processes : ";
cin>>p;
cout<<endl;
cout<<"Enter no. of blocks or partitions : ";
cin>>b;
cout<<endl;
cout<<"Enter all Block Sizes : ";
blockSize = new int[b];
for (int i = 0; i < b ; i++)
{
cin>>blockSize[i];
}
cout<<"\nEnter all Requested Process Sizes : ";
processSize = new int[p];
for (int i = 0; i < p ; i++)
{
cin>>processSize[i];
}
bestFit(blockSize, b, processSize, p);
return 0 ;
}