Thursday, 22 January 2015

CPU Scheduling algorithm - Shortest Job First(SJF) in Cpp


This is a Cpp program which implements one of the CPU Scheduling algorithm called Shortest Job First(SJF).

Shortest Job First algorithm reduces the waiting time but it is impossible to implement as the processor must know all the jobs/processes in advance.





PROGRAM :
#include <iostream>

using namespace std;

int main()
{
    int i,j,temp,temp2,n,bt[1000],wt[1000],a[10];
    float avgWt,totalWt=0;
    wt[1]=0;
    cout <<"Enter how many jobs ?\t";
    cin >> n;
    for(i=1; i<=n; i++)
    {
        cout <<"Enter burst time for job "<< i <<":\t";
        cin >> bt[i];
        a[i]=i; //stores job has how much burst  time in array  i
    }
    for(i=1; i<=n; i++) // ascending order of burst times and a[i]

        for(j=i; j<=n; j++)

            if(bt[i] > bt[j])
            {
                temp=bt[i];
                bt[i]=bt[j];
                bt[j]=temp;
                temp2=a[i];
                a[i]=a[j];
                a[j]=temp2;
            }


    cout <<"\nWaiting time for Job" << a[1] <<" : 0 units \t";
    for(i=2; i<=n; i++)
    {
        wt[i]=bt[i-1]+wt[i-1];
        cout <<"\nWaiting time for Job" << a[i]<< " : "<< wt[i]<<"units \t";
        totalWt = totalWt + wt[i];
    }
    cout <<"\n\nThe total waiting time : "<< totalWt << "\t";
    avgWt= totalWt/n;
    cout <<"\n\nAverage waiting time : "<< avgWt <<"\t\n\n";
    return 0;
}

OUTPUT : 
Cpp - CPU Scheduling algorithm (SJF)