简体   繁体   中英

SJF algorithm with arrival time not working properly

typedef struct{
int tL; //Arrival time
int rafaga,id,tE,tP; //burst,id,waitTime,TimeAround     
} process;

int main(int argc, char** argv) {
int n= 3;
int i,j,rafagasum=0,k=1,rafagacomp;
process p[n],aux;
char id []= {'A','B','C','D','E','F'};
for(i=0;i<n;i++)
{
    printf(" Process burst %d: ",i);
    scanf("%d",&p[i].rafaga);
    printf("Arrival time %d: ",i);
    scanf("%d",&p[i].tL);
    p[i].id=id[i];



}

//Sort by arrival time

for (i=0;i<n;i++){
    for(j=0;j<n;j++){
     if(p[i].tL<p[j].tL){
        aux=p[j];
        p[j]=p[i];
        p[i]=aux;


     }

    }
}

for(j=0;j<n;j++){
    rafagasum=rafagasum+p[j].rafaga;
    rafagacomp=p[k].rafaga;
for(i=k;i<n;i++)
{

    if(rafagasum>p[i].tL && p[i].rafaga<rafagacomp)
    aux=p[k];
    p[k]=p[i];
    p[i]=aux;
    }   
    k++;
}
 // We calculate waiting time
p[0].tE=0; 

int sum=0;
for(i=1;i<n;i++){  
sum=sum+p[i-1].rafaga;
p[i].tE=sum-p[i].tL;
}

//We calculate Timearound
    int sum1=0;
    for(i=0;i<n;i++){

    sum1=sum1+p[i].rafaga;
    p[i].tP=sum1-p[i].tL;
}

printf(" ID   Turnaround  TWAit  \n ");

   for(i=0;i<n;i++){
    printf("%c \t  %d \t  %d \t  \n", p[i].id,p[i].tP,p[i].tE);
      }



    return 0;
   }

I think most of you know what this algorithm (SJF) should do, I was told to code one and this is what I got. I decided to use a struct "process" which contains the times and id.

I think that the sort by arrival time is working just fine but sometimes, on the printf, I get 2 times the same letter (process) and the Timearound and Waiting times that I get are not right and I don't really know how to fix that since I think that the formulas I used are right. Any help would be nice.

Wherever it says "rafaga" that means "burst time"

In SJF algorithm,first you sort on the basis of arrival times followed by sorting on the basis of burst time .

Now looking at your sorting code, it seems you are using selection sort , and your code is not correct. The inner loop always begins from one index more than outer index therefore j = i + 1 , instead of j = 0 correct sorting is:

for (i = 0;i < n;i++){

    for(j = i+1;j < n;j++)
    {
     if(p[i].tL < p[j].tL){

     aux=p[j];
     p[j]=p[i];
     p[i]=aux;
     }

    }
}

Also your sort for burst time looks incorrect. Take care of these little things and your code will be correct. On a side note SJF is the simplest to code once you understand the basics.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM