JustPaste
HomeCategoriesAboutDonateContactTerms of UsePrivacy Policy
JustPaste

Free online notepad — write and share instantly

Navigate

  • Home
  • Timeline
  • Categories

Info

  • About
  • Donate
  • Contact

Legal

  • Terms of Use
  • Privacy Policy

© 2026 JustPaste.app. All rights reserved.

Made with ♥ by JustPaste

Best Fit, Worst Fit | JustPaste.app
1 day ago10 views
👨‍💻Programming

Best Fit, Worst Fit

#include <stdio.h>

int main()
{
    int b[20], p[20], alloc[20];
    int nb, np, i, j, best, worst;

    printf("Enter number of memory blocks: ");
    scanf("%d", &nb);

    printf("Enter sizes of memory blocks:\n");
    for(i = 0; i < nb; i++)
        scanf("%d", &b[i]);

    printf("Enter number of processes: ");
    scanf("%d", &np);

    printf("Enter sizes of processes:\n");
    for(i = 0; i < np; i++)
        scanf("%d", &p[i]);

    // FIRST FIT
    for(i = 0; i < np; i++)
        alloc[i] = -1;

    for(i = 0; i < np; i++)
    {
        for(j = 0; j < nb; j++)
        {
            if(b[j] >= p[i])
            {
                alloc[i] = j;
                b[j] -= p[i];
                break;
            }
        }
    }

    printf("\nFIRST FIT:\n");
    for(i = 0; i < np; i++)
        printf("Process %d -> %s\n", i + 1,
               alloc[i] == -1 ? "Not Allocated" : "Allocated");

    // Restore original block sizes
    printf("\nEnter original memory block sizes again:\n");
    for(i = 0; i < nb; i++)
        scanf("%d", &b[i]);

    // BEST FIT
    for(i = 0; i < np; i++)
        alloc[i] = -1;

    for(i = 0; i < np; i++)
    {
        best = -1;

        for(j = 0; j < nb; j++)
        {
            if(b[j] >= p[i] &&
               (best == -1 || b[j] < b[best]))
                best = j;
        }

        if(best != -1)
        {
            alloc[i] = best;
            b[best] -= p[i];
        }
    }

    printf("\nBEST FIT:\n");
    for(i = 0; i < np; i++)
        printf("Process %d -> %s\n", i + 1,
               alloc[i] == -1 ? "Not Allocated" : "Allocated");

    // Restore original block sizes
    printf("\nEnter original memory block sizes again:\n");
    for(i = 0; i < nb; i++)
        scanf("%d", &b[i]);

    // WORST FIT
    for(i = 0; i < np; i++)
        alloc[i] = -1;

    for(i = 0; i < np; i++)
    {
        worst = -1;

        for(j = 0; j < nb; j++)
        {
            if(b[j] >= p[i] &&
               (worst == -1 || b[j] > b[worst]))
                worst = j;
        }

        if(worst != -1)
        {
            alloc[i] = worst;
            b[worst] -= p[i];
        }
    }

    printf("\nWORST FIT:\n");
    for(i = 0; i < np; i++)
        printf("Process %d -> %s\n", i + 1,
               alloc[i] == -1 ? "Not Allocated" : "Allocated");

    return 0;
}
← Back to timeline