Implementation of Worst fit memory management in Python

Worst Fit memory management is a memory allocation algorithm where the largest available block of memory is allocated to a process requesting memory. It aims to maximize the utilization of memory by allocating the largest available block to a 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, -350, 200, -150, -100]

Explanation:

  • The first process of size 150 is allocated to the second memory block of size 250, leaving 100 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, leaving no memory unused.
  • The fourth process of size 100 is allocated to the first memory block of size 100, leaving no memory unused.

Implementation of Worst fit memory management in Python

Allocate memory to a process by selecting the largest available memory block.

Steps:

  1. Iterate through each process and find the largest available memory block that can accommodate it.
  2. Allocate the process to the selected memory block.
  3. If no suitable memory block is found, mark the process as unallocated.

Code Implementation:

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

    for i in range(len(process_sizes)):
        worst_fit_index = -1
        for j in range(len(memory_blocks)):
            if memory_blocks[j] >= process_sizes[i]:
                if worst_fit_index == -1 or memory_blocks[j] > memory_blocks[worst_fit_index]:
                    worst_fit_index = j

        if worst_fit_index != -1:
            allocation[i] = worst_fit_index
            memory_blocks[worst_fit_index] -= process_sizes[i]

    return allocation

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

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

Complexity Analysis:

  • Time Complexity: The worst-fit algorithm has a time complexity of O(nm), where ?n is the number of memory blocks and m is the number of processes. This is because we iterate through each process and, for each process, iterate through each memory block to find the worst fit.
  • Space Complexity: The space complexity is O(m), where ?m is the number of processes, as it stores the allocation status for each process

Contact Us