VOOZH about

URL: https://www.geeksforgeeks.org/dsa/program-for-next-fit-algorithm-in-memory-management/

⇱ Program for Next Fit algorithm in Memory Management - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Program for Next Fit algorithm in Memory Management

Last Updated : 25 Oct, 2025

The Next Fit algorithm is a modified version of the First Fit memory allocation technique. While the First Fit algorithm always starts searching from the beginning of the memory block list for each new process, the Next Fit algorithm optimizes this behavior by continuing the search from where it last left off.

Note: This is achieved by maintaining a roving pointer, which remembers the position of the last allocated block and begins the next search from there instead of restarting from the beginning.

Advantages of Next Fit over First Fit

  • Reduces fragmentation near the beginning: Unlike First Fit, which continuously fills the initial part of memory, Next Fit distributes allocations more evenly across the memory space.
  • Improved performance: Since it doesn’t restart the search every time, the average time to find a free block is reduced, making it faster than First Fit and Best Fit in many scenarios.
  • Better load balancing: Memory usage gets spread more uniformly, reducing the chances of creating too many small fragments in a specific region.

Example

Input:

Block sizes: [5, 10, 20]
Process sizes: [10, 20, 30]

Output:

Process No. Process Size Block No.
1 10 2
2 20 3
3 30 Not Allocated

Algorithm Steps

  1. Input the number and size of memory blocks.
  2. Mark all blocks as free.
  3. Input the number and size of processes.
  4. For each process: Check if it can be allocated in the current block.
  5. If yes, allocate and move the pointer to the current block.
  6. If not, continue checking further blocks in a circular fashion.
  7. Print the allocation results.
👁 frame_3199
Next Fit

Implementation


Output
Process No. Process Size Block no.
 1 10 2
 2 20 3
 3 5 1

Time and Space Complexity

  • Time Complexity: O(N × M) (For each process, in the worst case, the algorithm may traverse all blocks once.)
  • Auxiliary Space: O(N) (For storing allocation results.)

How Next Fit Reduce Fragmentation

The Next Fit algorithm helps in reducing external fragmentation by:

  • Avoiding repeated use of initial memory blocks.
  • Spreading allocations more evenly across memory.
  • Leaving larger free gaps between allocated partitions that can accommodate future large processes.

Note: By doing so, it minimizes the number of small unusable fragments that typically occur at the beginning of the memory in First Fit.

Comment
Article Tags:
Article Tags: