There are several issues and inaccuracies in your code which need to be addressed to correctly implement the Shortest Job First (SJF) scheduling algorithm. Below, I'm presenting a revised version of your program with explanations for the main points that were corrected or improved:
- The loop for sorting
ar[] array has an infinite loop because h variable is never incremented. It should be h++ instead of h+1. However, to simplify, I suggest using a more simple sorting method directly on the p[] array.
- The original algorithm for calculating waiting and turnaround times doesn't correctly follow the SJF logic. It compares burst times from the sorted
ar[] array and p[] array, which does not guarantee the correct process order because of potential duplicate burst times.
- Instead of relying on a separate array (
ar[]) for sorting, it's more straightforward to sort the p[] structures based on bursttime directly.
- The program should calculate waiting times and turnaround times after sorting the processes according to their burst times to adhere to SJF scheduling correctly.
Here's a revised version of your code:
#include <stdio.h>
struct sjfs {
int totaltime;
int bursttime;
int waitingtime;
} p[10];
void swap(struct sjfs *xp, struct sjfs *yp) {
struct sjfs temp = *xp;
*xp = *yp;
*yp = temp;
}
// Function to perform selection sort on `p[]` based on `bursttime`
void sortProcessesByBurstTime(struct sjfs p[], int n) {
int i, j, min_idx;
for (i = 0; i < n-1; i++) {
min_idx = i;
for (j = i + 1; j < n; j++)
if (p[j].bursttime < p[min_idx].bursttime)
min_idx = j;
swap(&p[min_idx], &p[i]);
}
}
void calculateTimes(struct sjfs p[], int n) {
p[0].waitingtime = 0; // first process always has 0 waiting time
p[0].totaltime = p[0].bursttime; // turnaround time when coming first
// Calculating waiting time
for (int i = 1; i < n; i++) {
p[i].waitingtime = p[i-1].waitingtime + p[i-1].bursttime;
p[i].totaltime = p[i].waitingtime + p[i].bursttime;
}
}
int main(){
int n, i;
float average = 0;
printf("Enter the number of processes: ");
scanf("%d", &n);
for (i = 0; i < n; i++){
printf("Enter the burst time for process %d: ", i+1);
scanf("%d", &p[i].bursttime);
}
sortProcessesByBurstTime(p, n);
calculateTimes(p, n);
int totalWaitingTime = 0;
printf("\n");
for (i = 0; i < n; i++){
printf("Process %d - Waiting Time: %d, Turnaround Time: %d\n",
i + 1, p[i].waitingtime, p[i].totaltime);
totalWaitingTime += p[i].waitingtime;
}
average = (float)totalWaitingTime / n;
printf("The average waiting time is: %.2f\n", average);
return 0;
}
This revised code simplifies the sorting by directly sorting the processes based on their bursttime. It then calculates waiting times and total times (turnaround times) in a linear way following the SJF scheduling logic.