Implementation of First Fit Memory Management in Python

First Fit memory management is a technique used in operating systems for allocating memory to processes. When a process requests memory, the allocator searches the available memory blocks from the beginning of the memory and allocates the first block that is large enough to accommodate the process.

Examples:

Let’s consider an example with memory blocks of sizes [100, 250, 200, 300, 150] and process sizes [150, 350, 200, 100].

Input: Memory Blocks: [100, 250, 200, 300, 150], Process Sizes: [150, 350, 200, 100]

Output: Memory Allocation: [100, -200, 200, -100, 150]

Explanation:

  • The first process of size 150 is allocated to the first memory block of size 100, leaving 50 units of memory unused.
  • The second process of size 350 cannot be allocated to any block, so it remains unallocated.
  • The third process of size 200 is allocated to the third memory block of size 200.
  • The fourth process of size 100 is allocated to the fifth memory block of size 150, leaving 50 units of memory unused.

Implementation of First Fit Memory Management in Python

Python
def first_fit(memory_blocks, process_sizes):
    allocation = [-1] * len(process_sizes)

    for i in range(len(process_sizes)):
        for j in range(len(memory_blocks)):
            if memory_blocks[j] >= process_sizes[i]:
                allocation[i] = j
                memory_blocks[j] -= process_sizes[i]
                break

    return allocation

# Example usage
memory_blocks = [100, 250, 200, 300, 150]
process_sizes = [150, 350, 200, 100]
allocation = first_fit(memory_blocks, process_sizes)
print("Memory Allocation:", allocation)

Output
Memory Allocation: [1, -1, 2, 0]

Complexity Analysis

Time Complexity:

  • The time complexity of the First Fit algorithm depends on the number of memory blocks and process sizes. In the worst case, it can be O(n×m), where ?n is the number of memory blocks and ?m is the number of process sizes.

Space Complexity:

  • The space complexity is O(m), where ?m is the number of process sizes, as it stores the allocation status for each process.

Contact Us