SJF Scheduling Algorithm
Shortest Job First is a CPU scheduling algorithm where the CPU execute the process first which have the shorest burst time.
Code
/***Scheduling algorithm for SJF***/
#include <stdio.h>
#include <malloc.h>
int main()
{
int n,*b,*w,*a,i,j,h,t,tt;
float avg =0;
printf("\nEnter the numbers of jobs:");
scanf("%d",&n);
b=(int *)malloc(n*sizeof(int)); //Array for holding the burst time of the jobs
w=(int *)malloc(n*sizeof(int)); //Array for holding the waiting time of the jobs
a=(int *)malloc(n*sizeof(int)); //Array for holding the jobs number according their appearance
//Taking the burst time from the user
printf("\nEnter the burst time for corresponding jobs:");
for(i=1;i<=n;i++)
{
printf("\nProcess %d:",i);
scanf("%d",&b[i]);
a[i]=i;
}
for(i=1;i<=n;i++)
{
for(j=i;j<=n;j++)
{
//Shorting the process according to their burst time in ascending order
if(b[i]>b[j])
{
t=b[i];tt=a[i];
b[i]=b[j];a[i]=a[j];
b[j]=t;a[j]=tt;
}
//If both process has same burst time then short them according their appearance
if(b[i]==b[j])
{
if(a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
}
w[1]=0;
printf("\nProcess %d waiting time is 0",a[1]); //The first process waiting time is always 0
for(i=2;i<=n;i++)
{
w[i]=b[i-1]+w[i-1]; //Calculate the waiting time of the i'th process
printf("\nProcess %d waiting time is %d",a[i],w[i]); //Print the waiting time
avg+=w[i]; //Calculate the total waiting time
}
printf("\nTotal waiting time :%f",avg); //Print the total waiting time
printf("\nThe average waiting time :%f",avg/n);//Print the average waiting time
return 0;
}
Output
Enter the numbers of jobs:5 Enter the burst time for corresponding jobs: Process 1:4 Process 2:3 Process 3:6 Process 4:2 Process 5:1 Process 5 waiting time is 0 Process 4 waiting time is 1 Process 2 waiting time is 3 Process 1 waiting time is 6 Process 3 waiting time is 10 Total waiting time :20.000000 The average waiting time :4.000000