(Open in Desktop/Laptop/Big Screen  for better result.)

Title: Write a program to implement Shortest Job First Scheduling Algorithm. Calculate
average waiting time, average turnaround time and throughput students.

Theory:

    ➤ Shortest Job First (SJF) Scheduling algorithm:
             Shortest Job First (SJF) is an algorithm in which the process having the smallest execution time is chosen for the next execution. This scheduling method can be preemptive or non-preemptive. It significantly reduces the average waiting time for other processes awaiting
execution. The full form of SJF is Shortest Job First.

   ➤  Code / Program:
  
          #include<stdio.h>
     int main()
     {
       int bt[20],p[20],wt[20],tat[20],i,j,n,total=0,pos,temp;
       float avg_wt,avg_tat;

       printf("Enter number of process:");
       scanf("%d",&n);

       printf("nEnter Burst Time:n");
       for(i=0;i<n;i++)
         {
           printf("p%d:",i+1);
           scanf("%d",&bt[i]);
           p[i]=i+1;
         }

     //sorting of burst times
     for(i=0;i<n;i++)
      {
        pos=i;
        for(j=i+1;j<n;j++)
          {
            if(bt[j]<bt[pos])
            pos=j;
          }

       temp=bt[i];
       bt[i]=bt[pos];
       bt[pos]=temp;
       temp=p[i];
       p[i]=p[pos];
       p[pos]=temp;
    }

  wt[0]=0;
  for(i=1;i<n;i++)
    {
      wt[i]=0;
      for(j=0;j<i;j++)
      wt[i]+=bt[j];
      total+=wt[i];
    }

  avg_wt=(float)total/n;
  total=0;
  printf("nProcesst Burst Time tWaiting TimetTurnaround Time");

  for(i=0;i<n;i++)
    {
     tat[i]=bt[i]+wt[i];
     total+=tat[i];
     printf("np%dtt %dtt %dttt%d",p[i],bt[i],wt[i],tat[i]);
    }

   avg_tat=(float)total/n;
   printf("nnAverage Waiting Time=%f",avg_wt);
   printf("nAverage Turnaround Time=%fn",avg_tat);
}

Output:


Observations / Results:



 Gantt Chart:
     

  I) Average waiting time:
      First calculate waiting time of each process Therefore,
      Waiting time: P4 = 0; P1 = 1 ; P2 = 4 ; P5 = 7 ; P3 = 14 ;
      Average Waiting time = (0+1+4+7+14)/5 = 5.2

 II) Average Turnaround time:
      First calculate turnaround time of each process, Therefore,
      Turnaround time: P4 = 3 ; P1 = 7 ; P2 = 6 ; P5 = 11 ; P3 = 22;
      Average Turnaround time = (3+7+6+11+22)/5 = 9.8

III) Throughtput = 5/23 = 0.217391304

Conclusion:

  ➤ Advantages of SJF scheduling algorithm:
         I) Shortest job are favored.
         II) It is provably optimal, in that it gives the minimum average waiting time for    a given set of processes.  

  ➤ Disadvantages / Limitation of SJF scheduling algorithm:
         I) SJF may cause starvation, if shorter processes keep coming. This problem is solved by aging.
        II) It cannot be implemented at the level of short term CPU scheduling.