Program for Best Fit algorithm in Memory Management | Function to allocate memory to blocks as per Best fit algorithm ; Stores block id of the block allocated to a 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
def bestFit ( blockSize , m , processSize , n ) : NEW_LINE INDENT allocation = [ - 1 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT bestIdx = - 1 NEW_LINE for j in range ( m ) : NEW_LINE INDENT if blockSize [ j ] >= processSize [ i ] : NEW_LINE INDENT if bestIdx == - 1 : NEW_LINE INDENT bestIdx = j NEW_LINE DEDENT elif blockSize [ bestIdx ] > blockSize [ j ] : NEW_LINE INDENT bestIdx = j NEW_LINE DEDENT DEDENT DEDENT if bestIdx != - 1 : NEW_LINE INDENT allocation [ i ] = bestIdx NEW_LINE blockSize [ bestIdx ] -= processSize [ i ] NEW_LINE DEDENT DEDENT print ( " Process ▁ No . ▁ Process ▁ Size ▁ Block ▁ no . " ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( i + 1 , " ▁ " , processSize [ i ] , end = " ▁ " ) NEW_LINE if allocation [ i ] != - 1 : NEW_LINE INDENT print ( allocation [ i ] + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not ▁ Allocated " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT blockSize = [ 100 , 500 , 200 , 300 , 600 ] NEW_LINE processSize = [ 212 , 417 , 112 , 426 ] NEW_LINE m = len ( blockSize ) NEW_LINE n = len ( processSize ) NEW_LINE bestFit ( blockSize , m , processSize , n ) NEW_LINE DEDENT