C Program for Shortest Job First (SJF) CPU Scheduling
Subject: OS (Operating Systems)
Contributed By: Nunugoppula Ajay
Created At: March 6, 2025
Question:
Write a C Program for Shortest Job First (SJF) CPU Scheduling in OS
Explanation Video:

Explanation:
Shortest Job First (SJF) CPU Scheduling Algorithm
Shortest Job First Algorithm works based on short burst times, it first executes the shortest job and after execution, it picks up the next shortest job for execution. This goes on till all the processes are executed.
(NOTE: We can calculate the FCFS based on arrival time at ‘0’ for all processes, and for different arrival times for each process. Here in this article, we are going to consider all process arrivals at time ‘0’ .)
/SJF_Scheduling_Algorithm_Example_1.png)
Source Code:
#include <stdio.h>
#include <stdlib.h>
// Structure to store process details
struct Process {
int id; // Process ID
int bt; // Burst Time
int wt; // Waiting Time
int tat; // Turnaround Time
};
// Function to implement Shortest Job First (SJF) scheduling
void SJF(struct Process p[], int n) {
int total_wt = 0, total_tat = 0;
// Sorting processes by Burst Time (SJF - Non-Preemptive)
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (p[i].bt > p[j].bt) {
// Swap entire process structures
struct Process temp = p[i];
p[i] = p[j];
p[j] = temp;
}
}
}
// First process has zero waiting time
p[0].wt = 0;
// Calculate waiting time for each process
for (int i = 1; i < n; i++) {
p[i].wt = p[i - 1].wt + p[i - 1].bt;
total_wt += p[i].wt;
}
// Calculate turnaround time for each process
for (int i = 0; i < n; i++) {
p[i].tat = p[i].wt + p[i].bt;
total_tat += p[i].tat;
}
// Calculate average waiting and turnaround times
float avg_wt = (float)total_wt / n;
float avg_tat = (float)total_tat / n;
// Display process details
printf("\nProcess\tBurst Time\tWaiting Time\tTurnaround Time\n");
printf("-------------------------------------------------\n");
for (int i = 0; i < n; i++) {
printf("%d\t%d\t\t%d\t\t%d\n", p[i].id, p[i].bt, p[i].wt, p[i].tat);
}
printf("\nAverage Waiting Time: %.2f\n", avg_wt);
printf("Average Turnaround Time: %.2f\n", avg_tat);
}
int main() {
int n;
// Input number of processes
printf("Enter the number of processes: ");
scanf("%d", &n);
struct Process p[n];
// Input burst time for each process
printf("Enter Burst Time for each process:\n");
for (int i = 0; i < n; i++) {
p[i].id = i + 1; // Assign process ID
printf("Process %d Burst Time: ", p[i].id);
scanf("%d", &p[i].bt);
}
// Call SJF scheduling function
SJF(p, n);
return 0;
}
Input:
Enter the number of processes: 3
Enter Burst Time for each process:
Process 1 Burst Time: 6
Process 2 Burst Time: 2
Process 3 Burst Time: 8
Output:
Process Burst Time Waiting Time Turnaround Time
-------------------------------------------------
2 2 0 2
1 6 2 8
3 8 8 16
Average Waiting Time: 3.33
Average Turnaround Time: 8.67