Tuesday, 10 September 2013

Shortest Job First Preemptive Program in C

#include<stdio.h>
#include<iostream.h>

typedef struct process
{
int at,bt,wt;
}Process;
void sortProcess(Process p[],int n)
{
int i,j;
for(i=0;i<n-1;i++)
for(j=0;j<n-i-1;j++)
if(p[j].at > p[j+1].at)
{
Process temp = p[j];
p[j] = p[j+1];
p[j+1] = temp;
}
}
int get_minBT(Process p[],int n,int time)
{
int index=0,i;
int min = 32000;
for(i=0; i<n && p[i].at<=time ;i++)
{
if(p[i].bt<min && p[i].bt!=0)
{
min = p[i].bt;
index = i;
}
}
return index;
}

int main()
{
int i,j,n,ttime=0;
Process p[10];
cout<<"Enter the no. of processes: ";
cin>>n;
for(i=0;i<n;i++)
{
cout<<"Process "<<i+1<<endl;
cout<<"Arrivl Time: ";
cin>>p[i].at;
cout<<"Burst Time: ";
cin>>p[i].bt;
p[i].wt = 0;
ttime += p[i].bt;
}
sortProcess(p,n);

int time;
for(time = 0;time<ttime;time++)
{
int index = get_minBT(p,n,time);
p[index].bt--;

for(i=0;i<n && p[i].at<=time;i++)
{
if(i!=index && p[i].bt!=0)
p[i].wt++;
}
}

int btotal=0;
for(i=0;i<n;i++)
btotal += p[i].wt;
cout<<endl<<"Total Waiting  time: "<<btotal;
cout<<endl<<"Average Waiting time: "<<btotal/n;

return 0;
}

No comments: