Posts

Search

Best Fit

QUESTION DESCRIPTION

Write a C program for implementing the Best Fit algorithm in memory partitioning. The Best Fit Memory Allocation Algorithm allocates the smallest free partition available in the memory that is sufficient enough to hold the process within the system

TEST CASE 1

INPUT
5 4
10 2 5 12 7
4 1 11 6
OUTPUT
Process1 is allocated to Block3
after p1: 10 2 1 12 7
Process2 is allocated to Block3
after p1: 10 2 0 12 7
Process3 is allocated to Block4
after p1: 10 2 0 1 7
Process4 is allocated to Block5
after p1: 10 2 0 1 1

TEST CASE 2

INPUT
5 4
5 2 7 6 3 1
4 3 5 9
OUTPUT
Process1 is allocated to Block2
after p1: 5 1 7 6 3
Process2 is allocated to Block1
after p1: 1 1 7 6 3
Process3 is allocated to Block5
after p1: 1 1 7 6 0
Process4 is allocated to Block4
after p1: 1 1 7 1 0

Code :

#include <iostream>
#include<climits>
using namespace std;
int main() {
 int n,m,i,j,min,ind;
   cin>>n>>m;
   int a[n],b[m];
    for(i=0;i<n;i++)
     cin>>a[i];
   for(i=0;i<m;i++)
       cin>>b[i];
   for(i=0;i<m;i++){
       min=INT_MAX;
       ind=n;
       for(j=0;j<n;j++){
           if(a[j]>=b[i] && a[j]<min){
               min=a[j];
                ind=j;
   }
        }
       if(ind<n){
        a[ind]-=b[i];
            cout<<"Process"<<i+1<<" is allocated to Block"<<ind+1<<endl;
            cout<<"after p1:";
            for(j=0;j<n;j++)
              cout<<" "<<a[j];
            cout<<endl;
        }
       else{
           a[0]-=b[i];
           cout<<"Process"<<i+1<<" is allocated to Block1"<<endl;
            cout<<"after p1:";
            for(j=0;j<n;j++)
              cout<<" "<<a[j];
            cout<<endl;
        }
    }
 return 0;
}