Program for Worst Fit algorithm in Memory Management | C ++ implementation of worst - Fit algorithm ; Function to allocate memory to blocks as per worst fit algorithm ; Stores block id of the block allocated to a process ; Initially no block is assigned to any process ; pick each process and find suitable blocks according to its size ad assign to it ; Find the best fit block for current process ; If we could find a block for current process ; allocate block j to p [ i ] process ; Reduce available memory in this block . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void worstFit ( int blockSize [ ] , int m , int processSize [ ] , int n ) { int allocation [ n ] ; memset ( allocation , -1 , sizeof ( allocation ) ) ; for ( int i = 0 ; i < n ; i ++ ) { int wstIdx = -1 ; for ( int j = 0 ; j < m ; j ++ ) { if ( blockSize [ j ] >= processSize [ i ] ) { if ( wstIdx == -1 ) wstIdx = j ; else if ( blockSize [ wstIdx ] < blockSize [ j ] ) wstIdx = j ; } } if ( wstIdx != -1 ) { allocation [ i ] = wstIdx ; blockSize [ wstIdx ] -= processSize [ i ] ; } } cout << " Process No . Process Size Block no . " ; for ( int i = 0 ; i < n ; i ++ ) { cout << " ▁ " << i + 1 << " TABSYMBOL TABSYMBOL " << processSize [ i ] << " TABSYMBOL TABSYMBOL " ; if ( allocation [ i ] != -1 ) cout << allocation [ i ] + 1 ; else cout << " Not ▁ Allocated " ; cout << endl ; } } int main ( ) { int blockSize [ ] = { 100 , 500 , 200 , 300 , 600 } ; int processSize [ ] = { 212 , 417 , 112 , 426 } ; int m = sizeof ( blockSize ) / sizeof ( blockSize [ 0 ] ) ; int n = sizeof ( processSize ) / sizeof ( processSize [ 0 ] ) ; worstFit ( blockSize , m , processSize , n ) ; return 0 ; }