Write a program using C to implement Shortest Job First (SJF) scheduling algorithm.
Below is the C program that implements the Shortest Job First (SJF) scheduling algorithm. This scheduling algorithm selects the process that has the smallest burst time for execution next.
#include <stdio.h>
struct Process {
int id; // Process ID
int burst; // Burst time
int waiting; // Waiting time
int turnaround; // Turnaround time
};
// Function to calculate waiting and turnaround times
void calculateTimes(struct Process processes[], int n) {
int total_waiting = 0, total_turnaround = 0;
// Calculate waiting time for each process
for (int i = 0; i < n; i++) {
if (i == 0) {
processes[i].waiting = 0; // First process has no waiting time
} else {
processes[i].waiting = processes[i - 1].waiting + processes[i - 1].burst;
}
total_waiting += processes[i].waiting;
processes[i].turnaround = processes[i].waiting + processes[i].burst;
total_turnaround += processes[i].turnaround;
}
// Print average waiting and turnaround times
printf("Average Waiting Time: %.2f\n", (float)total_waiting / n);
printf("Average Turnaround Time: %.2f\n", (float)total_turnaround / n);
}
// Function to sort processes by burst time
void sortProcesses(struct Process processes[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (processes[i].burst > processes[j].burst) {
struct Process temp = processes[i];
processes[i] = processes[j];
processes[j] = temp;
}
}
}
}
// Function to print process details
void printProcessDetails(struct Process processes[], int n) {
printf("\nProcess ID\tBurst Time\tWaiting Time\tTurnaround Time\n");
for (int i = 0; i < n; i++) {
printf("%d\t\t%d\t\t%d\t\t%d\n",
processes[i].id, processes[i].burst,
processes[i].waiting, processes[i].turnaround);
}
}
int main() {
int n;
// Read the number of processes
printf("Enter the number of processes: ");
scanf("%d", &n);
struct Process processes[n];
// Read process burst times
for (int i = 0; i < n; i++) {
processes[i].id = i + 1; // Assign Process ID
printf("Enter burst time for Process %d: ", i + 1);
scanf("%d", &processes[i].burst);
}
// Sort processes by burst time
sortProcesses(processes, n);
// Calculate waiting and turnaround times
calculateTimes(processes, n);
// Print the process details
printProcessDetails(processes, n);
return 0;
}