Skip to main content

Implementing SJF (Shortest Job First) Scheduling in C++ with SRTF and Gantt Chart

Two complete C++ programs for non-preemptive SJF and preemptive SRTF scheduling that handle arrival times correctly, with Gantt charts, waiting/turnaround tables, a fix for the common sort-by-burst bug, and viva questions.

The Shortest Job First (SJF) scheduler always gives the CPU to the waiting process with the smallest burst time. Among all non-preemptive schedulers it gives the smallest possible average waiting time, which is why it shows up in almost every Operating Systems lab and exam.

This post gives you two complete C++ programs: non-preemptive SJF and its preemptive version, SRTF (Shortest Remaining Time First). Both handle arrival times correctly, print the waiting/turnaround table, and draw the Gantt chart. Every output below was produced by running the code, and the files are linked.

Tested with: g++ 13.3.0 (Ubuntu 24.04), -std=c++17 -Wall -Wextra, no warnings. Sources and all captured output: cs-lab-programs/os/sjf.

What SJF actually does

Picture a queue at a ticket counter where the clerk serves whoever needs the least time first. Short customers leave quickly, so the average wait across everyone drops. The price is that a customer with a long request can be pushed back again and again. This is called starvation.

Two rules decide everything:

  • Non-preemptive SJF: when the CPU becomes free, pick the arrived process with the smallest burst time and let it run to the end.
  • Preemptive SJF (SRTF): whenever a process arrives, compare its burst with what the running process still has left. If the newcomer is smaller, it takes the CPU immediately.

Three formulas are used in every table below:

  • Turnaround time = Completion time − Arrival time
  • Waiting time = Turnaround time − Burst time
  • Average = sum over all processes ÷ number of processes
Going deeper: why SJF is optimal, and why nobody can run it exactly

Suppose a long job runs just before a short one. Swapping them makes the short job finish sooner and delays the long one by only the short job’s length, so the sum of waiting times never gets worse. Repeating such swaps ends with the jobs in shortest-first order. That exchange argument is the standard proof, and it holds when all jobs are available at the same time.

The catch is that the scheduler must know each burst time in advance. Real systems estimate it with an exponential average of previous bursts: next = α × last + (1 − α) × previous_estimate.

A bug in the usual lab program (including the earlier version of this post)

Most textbook programs, and the earlier version of this post, sort all processes by burst time and then compute waiting times from that sorted order. That works only when every process arrives at time 0. As soon as arrival times differ, it schedules a process before it has arrived.

Here are four processes: P1 (arrival 0, burst 7), P2 (2, 4), P3 (4, 1), P4 (5, 4). The old program printed this (from 07-legacy-wrong-result.txt):

 Result (sorted by burst time — shortest first)
 PNO	AT	WT	BT	TT
 P3	4	0	1	1
 P2	2	3	4	7
 P4	5	4	4	8
 P1	0	13	7	20
 Total Burst Time: 16
 Average Waiting Time    : 5
 Average Turnaround Time : 9

It put P3 first, although P3 only arrives at time 4, and it says P1 waited 13 units. In reality P1 is the only process present at time 0, so it starts immediately with a wait of 0. The corrected program prints this for the same input (08-sjf-same-input-corrected.txt):

Non-preemptive SJF

PID	AT	BT	CT	TAT	WT
P1	0	7	7	7	0
P2	2	4	12	10	6
P3	4	1	8	4	3
P4	5	4	16	11	7

Average waiting time    : 4.00
Average turnaround time : 8.00

Gantt chart:
| P1 | P3 | P2 | P4 |
0    7    8    12   16
Fingerprint of this bug: a process with a late arrival time shows a waiting time of 0, or the first process in the sorted table is not the one that arrived first. If your lab answer has that, check whether you sorted by burst time without looking at arrival time.

The fix is to stop sorting once and instead make a fresh decision every time the CPU becomes free. That is what the next section does.

Non-preemptive SJF in C++

The loop keeps a clock called time. Each pass picks, from the processes that have already arrived (at <= time), the one with the smallest burst, runs it to completion, and records the slice for the Gantt chart. If nobody has arrived yet, the CPU idles until the next arrival. The full file is sjf_nonpreemptive.cpp.

// Shortest Job First (SJF) - NON-preemptive, with arrival times and a Gantt chart.
// At every decision point, pick the arrived, unfinished process with the smallest burst time.
// Ties are broken by earlier arrival, then by lower process number.
#include <algorithm>
#include <climits>
#include <iomanip>
#include <iostream>
#include <vector>
using namespace std;

struct Process {
    int pid, at, bt;
    int ct = 0, tat = 0, wt = 0;   // completion, turnaround, waiting
    bool done = false;
};

struct Slice { int pid, start, end; };   // pid = 0 means CPU idle

int main() {
    int n;
    cin >> n;
    vector<Process> p(n);
    for (int i = 0; i < n; i++) { p[i].pid = i + 1; cin >> p[i].at >> p[i].bt; }

    vector<Slice> gantt;
    int time = 0, finished = 0;
    while (finished < n) {
        int pick = -1;
        for (int i = 0; i < n; i++) {
            if (p[i].done || p[i].at > time) continue;
            if (pick == -1 || p[i].bt < p[pick].bt ||
                (p[i].bt == p[pick].bt && p[i].at < p[pick].at)) pick = i;
        }
        if (pick == -1) {                       // nobody has arrived: CPU idles to next arrival
            int next = INT_MAX;
            for (auto& q : p) if (!q.done) next = min(next, q.at);
            gantt.push_back({0, time, next});
            time = next;
            continue;
        }
        gantt.push_back({p[pick].pid, time, time + p[pick].bt});
        time += p[pick].bt;                     // runs to completion: non-preemptive
        p[pick].ct = time;
        p[pick].tat = p[pick].ct - p[pick].at;
        p[pick].wt = p[pick].tat - p[pick].bt;
        p[pick].done = true;
        finished++;
    }

    cout << "Non-preemptive SJF\n\n";
    cout << "PID\tAT\tBT\tCT\tTAT\tWT\n";
    double sw = 0, st = 0;
    for (auto& q : p) {
        cout << "P" << q.pid << "\t" << q.at << "\t" << q.bt << "\t" << q.ct << "\t" << q.tat << "\t" << q.wt << "\n";
        sw += q.wt; st += q.tat;
    }
    cout << fixed << setprecision(2);
    cout << "\nAverage waiting time    : " << sw / n << "\n";
    cout << "Average turnaround time : " << st / n << "\n\nGantt chart:\n";
    string top, nums;
    auto putNum = [&](int v) { nums += to_string(v); };
    for (auto& s : gantt) {
        string label = (s.pid ? "P" + to_string(s.pid) : string("idle"));
        if (nums.size() < top.size()) nums += string(top.size() - nums.size(), ' ');
        putNum(s.start);
        top += "| " + label + " ";
    }
    top += "|";
    if (nums.size() < top.size() - 1) nums += string(top.size() - 1 - nums.size(), ' ');
    putNum(gantt.back().end);
    cout << top << "\n" << nums << "\n";
}

Run 1: everyone arrives at time 0

This is the classic exam case (input file all-at-zero.txt). Output is from 01-sjf-all-at-zero.txt:

Non-preemptive SJF

PID	AT	BT	CT	TAT	WT
P1	0	5	12	12	7
P2	0	3	3	3	0
P3	0	8	20	20	12
P4	0	4	7	7	3

Average waiting time    : 5.50
Average turnaround time : 10.50

Gantt chart:
| P2 | P4 | P1 | P3 |
0    3    7    12   20
P20P43P17P31220Shortest burst first: P2(3), P4(4), P1(5), P3(8). Average waiting time 5.50.

The chart shows the order the CPU served the processes. P2 has the smallest burst so it goes first; P3 has the largest so it waits 12 units. Compare with first-come-first-served on the same input (order P1, P2, P3, P4): average waiting time is (0+5+8+16)/4 = 7.25, so SJF cuts it to 5.50.

Run 2: processes arrive at different times

Input staggered.txt; output 02-sjf-staggered.txt:

Non-preemptive SJF

PID	AT	BT	CT	TAT	WT
P1	0	7	7	7	0
P2	2	4	15	13	9
P3	4	1	8	4	3
P4	5	4	19	14	10
P5	6	3	11	5	2

Average waiting time    : 4.80
Average turnaround time : 8.60

Gantt chart:
| P1 | P3 | P5 | P2 | P4 |
0    7    8    11   15   19
P10P37P58P211P41519At time 7 only P2, P3, P4, P5 are waiting. Smallest burst wins: P3(1), then P5(3), then P2 and P4 tie at 4, and P2 arrived first.

P1 is the only process at time 0, so it must start even though its burst is the largest. Once it ends at 7, four processes are waiting and the scheduler picks the smallest each time. P2 and P4 both need 4 units; the code breaks the tie in favour of the earlier arrival (P2).

Idle time: if the ready queue is empty the CPU does nothing until the next arrival. With P1(0,2), P2(6,3), P3(7,1) the chart contains an idle slice from 2 to 6 (06-sjf-idle-gap.txt):

Non-preemptive SJF

PID	AT	BT	CT	TAT	WT
P1	0	2	2	2	0
P2	6	3	9	3	0
P3	7	1	10	3	2

Average waiting time    : 0.67
Average turnaround time : 2.67

Gantt chart:
| P1 | idle | P2 | P3 |
0    2      6    9    10

Preemptive SJF (SRTF) in C++

SRTF simulates one time unit per loop pass. At every tick it re-picks the arrived process with the least remaining time, so a new short job can interrupt a long running one. Consecutive ticks of the same process are merged into one Gantt slice. Source: srtf_preemptive.cpp.

// Shortest Remaining Time First (SRTF) - PREEMPTIVE SJF, simulated one time unit at a time.
// At every tick, run the arrived process with the least remaining time. A newly arrived
// process with a smaller remaining time preempts the running one.
#include <climits>
#include <iomanip>
#include <iostream>
#include <vector>
using namespace std;

struct Process { int pid, at, bt, rem, ct = 0, tat = 0, wt = 0; };
struct Slice { int pid, start, end; };   // pid = 0 means idle

int main() {
    int n;
    cin >> n;
    vector<Process> p(n);
    for (int i = 0; i < n; i++) { p[i].pid = i + 1; cin >> p[i].at >> p[i].bt; p[i].rem = p[i].bt; }

    vector<Slice> gantt;
    int time = 0, finished = 0;
    while (finished < n) {
        int pick = -1;
        for (int i = 0; i < n; i++) {
            if (p[i].rem == 0 || p[i].at > time) continue;
            if (pick == -1 || p[i].rem < p[pick].rem ||
                (p[i].rem == p[pick].rem && p[i].at < p[pick].at)) pick = i;
        }
        int pid = (pick == -1) ? 0 : p[pick].pid;
        if (!gantt.empty() && gantt.back().pid == pid) gantt.back().end = time + 1;   // extend slice
        else gantt.push_back({pid, time, time + 1});
        if (pick != -1 && --p[pick].rem == 0) {
            p[pick].ct = time + 1;
            p[pick].tat = p[pick].ct - p[pick].at;
            p[pick].wt = p[pick].tat - p[pick].bt;
            finished++;
        }
        time++;
    }

    cout << "Preemptive SJF (SRTF)\n\n";
    cout << "PID\tAT\tBT\tCT\tTAT\tWT\n";
    double sw = 0, st = 0;
    for (auto& q : p) {
        cout << "P" << q.pid << "\t" << q.at << "\t" << q.bt << "\t" << q.ct << "\t" << q.tat << "\t" << q.wt << "\n";
        sw += q.wt; st += q.tat;
    }
    cout << fixed << setprecision(2);
    cout << "\nAverage waiting time    : " << sw / n << "\n";
    cout << "Average turnaround time : " << st / n << "\n\nGantt chart:\n";
    string top, nums;
    auto putNum = [&](int v) { nums += to_string(v); };
    for (auto& s : gantt) {
        string label = (s.pid ? "P" + to_string(s.pid) : string("idle"));
        if (nums.size() < top.size()) nums += string(top.size() - nums.size(), ' ');
        putNum(s.start);
        top += "| " + label + " ";
    }
    top += "|";
    if (nums.size() < top.size() - 1) nums += string(top.size() - 1 - nums.size(), ' ');
    putNum(gantt.back().end);
    cout << top << "\n" << nums << "\n";
}

Where preemption makes a difference

Take P1(0,8), P2(1,4), P3(2,2). Non-preemptive SJF cannot stop P1 once it starts (04-sjf-preemption-case.txt):

Non-preemptive SJF

PID	AT	BT	CT	TAT	WT
P1	0	8	8	8	0
P2	1	4	14	13	9
P3	2	2	10	8	6

Average waiting time    : 5.00
Average turnaround time : 9.67

Gantt chart:
| P1 | P3 | P2 |
0    8    10   14

SRTF on the same input (05-srtf-preemption-case.txt):

Preemptive SJF (SRTF)

PID	AT	BT	CT	TAT	WT
P1	0	8	14	14	6
P2	1	4	7	6	2
P3	2	2	4	2	0

Average waiting time    : 2.67
Average turnaround time : 7.33

Gantt chart:
| P1 | P2 | P3 | P2 | P1 |
0    1    2    4    7    14
P10P21P32P24P1714P2 preempts P1 at t=1, then P3 preempts P2 at t=2. Average waiting time drops from 5.00 to 2.67.

At t=1, P2 needs 4 while P1 still needs 7, so P2 takes over. At t=2, P3 needs 2 while P2 has 3 left, so P3 takes over. The cost is more context switches (four here, against two in the non-preemptive run), which real systems must pay for.

Both algorithms on the five-process input

Output 03-srtf-staggered.txt:

Preemptive SJF (SRTF)

PID	AT	BT	CT	TAT	WT
P1	0	7	19	19	12
P2	2	4	7	5	1
P3	4	1	5	1	0
P4	5	4	14	9	5
P5	6	3	10	4	1

Average waiting time    : 3.80
Average turnaround time : 7.60

Gantt chart:
| P1 | P2 | P3 | P2 | P5 | P4 | P1 |
0    2    4    5    7    10   14   19
P10P22P34P25P57P410P11419P1 starts first but is pushed to the end: it is preempted at t=2 and only finishes at 19.
AlgorithmAvg waiting timeAvg turnaround timeLongest-burst process P1 waits
SJF (non-preemptive)4.808.600
SRTF (preemptive)3.807.6012

SRTF wins on the average, but look at the last column: the long process P1 pays for it. That is the starvation trade-off in numbers.

Going deeper: step-by-step trace of the five-process SJF run
  • t=0: only P1 has arrived, so P1 runs 0–7. Completion 7, turnaround 7, waiting 0.
  • t=7: waiting are P2(4), P3(1), P4(4), P5(3). Smallest is P3, runs 7–8. Waiting = 8−4−1 = 3.
  • t=8: waiting are P2(4), P4(4), P5(3). P5 runs 8–11. Waiting = 11−6−3 = 2.
  • t=11: P2 and P4 tie at 4; P2 arrived earlier, so P2 runs 11–15 (waiting 9), then P4 runs 15–19 (waiting 10).
  • Average waiting = (0+9+3+10+2)/5 = 4.80, matching the program.

The original version of this program

Show the original all-arrive-at-zero program (kept for reference)

This is the earlier code from this post, kept as legacy/old_sjf_sort_by_burst.cpp. It sorts by burst time with a selection sort and uses WT[i] = WT[i-1] + BT[i-1] - (AT[i] - AT[i-1]). It is correct only when all arrival times are equal, and it handles exactly 4 processes.

// ============================================================
// Shortest Job First (SJF) CPU Scheduling Algorithm in C++
// Non-preemptive: selects process with smallest burst time first
// ============================================================

#include <iostream>
using namespace std;

// Structure to group all attributes of a single process together
struct Process {
    int processNo;    // Original process number (preserved after sorting)
    int arrivalTime;  // Time at which process arrives in the ready queue
    int burstTime;    // CPU burst time required by the process
    int waitingTime;  // Time spent waiting before CPU is allocated
    int turnaroundTime; // Total time from arrival to completion
};

int main() {

    const int PROCESS_COUNT = 4;
    Process processes[PROCESS_COUNT];

    // -------------------------------------------------------
    // Step 1: Read arrival and burst times from the user
    // -------------------------------------------------------
    for (int i = 0; i < PROCESS_COUNT; i++) {
        cout << "\n Enter arrival time of P" << i + 1 << ": ";
        cin  >> processes[i].arrivalTime;
        cout << " Enter burst time of P"    << i + 1 << ": ";
        cin  >> processes[i].burstTime;
        processes[i].processNo = i + 1;  // Remember original process number
    }

    // Display the entered data before sorting
    cout << "\n\n Entered Data (before sorting)";
    cout << "\n PNO\tAT\tBT";
    for (int i = 0; i < PROCESS_COUNT; i++) {
        cout << "\n P" << processes[i].processNo
             << "\t" << processes[i].arrivalTime
             << "\t" << processes[i].burstTime;
    }

    // -------------------------------------------------------
    // Step 2: Sort processes by burst time (ascending = SJF order)
    // Uses selection sort; swaps entire Process struct to keep data intact
    // -------------------------------------------------------
    for (int outer = 0; outer < PROCESS_COUNT - 1; outer++) {
        for (int inner = outer + 1; inner < PROCESS_COUNT; inner++) {
            if (processes[outer].burstTime > processes[inner].burstTime) {
                // Swap the entire process record
                Process temp        = processes[outer];
                processes[outer]    = processes[inner];
                processes[inner]    = temp;
            }
        }
    }
    // After sorting: processes[0] has the shortest burst time

    // -------------------------------------------------------
    // Step 3: Compute Waiting Time and Turnaround Time
    // -------------------------------------------------------
    processes[0].waitingTime    = 0;                        // First job waits 0
    processes[0].turnaroundTime = processes[0].burstTime;   // TT = 0 + BT

    int totalBurstTime = processes[0].burstTime;

    for (int i = 1; i < PROCESS_COUNT; i++) {
        // WT[i] = WT[i-1] + BT[i-1] - gap in arrival times
        processes[i].waitingTime =
            processes[i-1].waitingTime + processes[i-1].burstTime
            - (processes[i].arrivalTime - processes[i-1].arrivalTime);

        // Guard: waiting time cannot go negative
        if (processes[i].waitingTime < 0) processes[i].waitingTime = 0;

        processes[i].turnaroundTime =
            processes[i].waitingTime + processes[i].burstTime;

        totalBurstTime += processes[i].burstTime;
    }

    // -------------------------------------------------------
    // Step 4: Print results
    // -------------------------------------------------------
    cout << "\n\n Result (sorted by burst time — shortest first)";
    cout << "\n PNO\tAT\tWT\tBT\tTT";
    for (int i = 0; i < PROCESS_COUNT; i++) {
        cout << "\n P" << processes[i].processNo
             << "\t" << processes[i].arrivalTime
             << "\t" << processes[i].waitingTime
             << "\t" << processes[i].burstTime
             << "\t" << processes[i].turnaroundTime;
    }
    cout << "\n Total Burst Time: " << totalBurstTime;

    // -------------------------------------------------------
    // Step 5: Compute averages
    // -------------------------------------------------------
    int totalWaiting = 0, totalTurnaround = 0;
    for (int i = 0; i < PROCESS_COUNT; i++) {
        totalWaiting    += processes[i].waitingTime;
        totalTurnaround += processes[i].turnaroundTime;
    }

    cout << "\n Average Waiting Time    : " << (float)totalWaiting    / PROCESS_COUNT;
    cout << "\n Average Turnaround Time : " << (float)totalTurnaround / PROCESS_COUNT;
    cout << endl;

    return 0;
}

With all arrivals at 0 it produced the same table as Run 1 above: waiting times 0, 3, 7, 12 and averages 5.5 and 10.5.

Viva questions with short answers

Show 10 viva questions
  1. Is SJF preemptive? The basic version is not. The preemptive version is called SRTF.
  2. Why does SJF give the minimum average waiting time? Running short jobs first lets the most processes finish early, so fewer processes wait behind long ones (exchange argument).
  3. What is starvation? A long job never gets the CPU because shorter jobs keep arriving.
  4. How do you fix starvation? Aging: raise a process’s priority the longer it waits.
  5. Main practical drawback? Burst time must be known in advance; it can only be estimated.
  6. How is the burst estimated? Exponential averaging of past bursts.
  7. What if two processes have the same burst? Break the tie by arrival time (FCFS), as this program does.
  8. Waiting time formula? Turnaround time − burst time.
  9. Which is better on average waiting time, SJF or SRTF? SRTF, at the cost of more context switches.
  10. Is SJF with all arrivals at 0 the same as sorting by burst? Yes. With different arrivals it is not, which is the bug shown above.
Should you use SJF in practice? Almost never exactly, because nobody knows burst times in advance. Real schedulers use feedback queues or time slicing (see Round Robin) and borrow the SJF idea through estimates. SJF is still worth learning because it is the yardstick other algorithms are compared against.

See also

No Comments yet!

This site uses Akismet to reduce spam. Learn how your comment data is processed.