I have created a C Program to simulate the Non-Preemptive Shortest Job First Algorithm but it has bugs with certain inputs. The shortest job first algorithm program takes in inputs for the arrival and burst times of the required number of processes and arranges the processes in 2 phases. The first phase involves arranging the program by arrival times and the 2nd phase arranges them by burst times given that their arrival times are lower than the time for the previous process to complete. This is all then compiled in the end and shown.
#include <stdio.h>// n - total processes// p - process no. array// bt - burst time array// at - arrival time array// wt - the time taken for the process to start from it's arrival time array// tat - time spent by process in cpu arrayint i, n, j, m, min, sum = 0, x = 1, btTally = 0, p[20], bt[20], at[20], wt[20], tat[20], ta = 0;float tatTally = 0, wtTally = 0;//function grabs arrival and burst times of each process and stores it in its respective arrayvoid getInput(){ printf("\nEnter the total number of processes: "); scanf("%d", & n); // For Loop for user to input info about the processes for (i = 0; i < n; i++) { p[i] = i + 1; printf("\nEnter the arrival time of process %d: ", p[i]); scanf(" %d", & at[i]); printf("\nEnter the burst time of process %d: ", p[i]); scanf(" %d", & bt[i]); }}//Function arranges processes according to their arrival timesvoid arrangePhase1(){ for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { if (at[j] > at[i]) { m = p[j]; p[j] = p[i]; p[i] = m; m = at[j]; at[j] = at[i]; at[i] = m; m = bt[j]; bt[j] = bt[i]; bt[i] = m; } } }}//Function arranges the processes according to Burst timevoid arrangePhase2(){ for (i = 0; i < n; i++) { btTally = btTally + bt[i]; min = bt[x]; for (j = x; j < n; j++) { if (bt[j] < min && btTally >= at[j]) { m = p[x]; p[x] = p[j]; p[j] = m; m = at[x]; at[x] = at[j]; at[j] = m; m = bt[x]; bt[x] = bt[j]; bt[j] = m; } } x++; }}//Function calculates the tallies of turnaround time and waiting timevoid calcTallies(){ for (i = 0; i < n; i++) { ta = ta + bt[i]; tat[i] = ta - at[i]; tatTally = tatTally + tat[i]; } wt[0] = 0; for (i = 1; i < n; i++) { sum = sum + bt[i - 1]; wt[i] = sum - at[i]; wtTally = wtTally + wt[i]; }}//Function displays all of the information about the algorithm runningvoid showFinal(){ printf("\nProcess\t Arrival Time\t Burst Time\t Waiting Time\t Turnaround Time"); for (i = 0; i < n; i++) { printf("\n p%d\t %d\t\t %d\t\t %d\t\t %d", p[i], at[i], bt[i], wt[i], tat[i]); } printf("\nAverage Waiting Time: %.2f", (wtTally / n)); printf("\nAverage Turn Around Time: %.2f", (tatTally / n));}int main() { getInput(); arrangePhase1(); arrangePhase2(); arrangePhase2(); calcTallies(); showFinal(); return 0;}
These are the expected results:
These are the results I get with my programme:
Any help would really be appreciated. Thanks!