GeeksforGeeks Medium

Shortest Job First

Shortest Job First is a GFG problem (Medium). You are given an array bt of burst times: bt[i] is how long process i needs the CPU. Every process is ready at time 0, and the CPU runs one process at a time, start to finish.

Schedule them by shortest job first (the shortest burst runs next) and return the average waiting time, rounded down to an integer.

  • A process's waiting time is how long it sits ready but not running. Here that is simply its start time.
  • n and each burst go up to 10⁵, so the total wait can reach about 5 × 10¹⁴.
Constraints
  • 1 <= n <= 10⁵
  • 1 <= bt[i] <= 10⁵
  • Every process is available at time 0
greedysortingscheduling
Open on GeeksforGeeks ↗
02

Intuition

Every job that runs adds its whole burst to the wait of every job behind it. So the order decides the total: a long job placed early is paid for by many jobs, while a long job placed last is paid for by none.

Running the jobs shortest first makes the delays that get counted most often the smallest ones. That is why SJF gives the lowest possible average waiting time. It is also non-preemptive: once a job starts, it runs to the end.

Because every job is ready at time 0, a job's wait is just the sum of the bursts that ran before it.

How to spot this pattern

Whenever jobs must be ordered to minimise the total or average of their waiting or finishing times, sort by duration: it is the same swap argument each time. It appears as SJF in operating-system questions, as "minimise total waiting time", and in scheduling with a single machine. If jobs arrive at different times, the order is no longer a plain sort (see the FAQ).

03

Approach

Try it first

Before reading on: for bursts [4, 1], work out the total waiting time if 4 runs first, and then if 1 runs first. What does the difference tell you about where long jobs belong?

1

Sort the burst times

Sort bt in increasing order. That is the whole schedule: index 0 runs first, then index 1, and so on. No job has to wait for an arrival, because all of them are ready at time 0.

2

Add up the start times

Keep clock, the time the CPU becomes free, and total, the waiting time so far. For each burst t in sorted order:

  • add clock to total, because this job waited from 0 until now;
  • then add t to clock, because the job runs for t.

The order of these two lines matters: a job does not wait for itself.

3

Return the average, rounded down

Return total // n. GFG asks for the nearest integer not above the average, which is integer division. In C++ and Java, keep clock and total in a 64-bit type, since the total can pass 2³¹.

4

Why shortest first is the best order

Take any order where a longer job L runs just before a shorter job S. Swapping them leaves every other job's wait the same, adds S to L's wait and removes L from S's wait, so the total drops by L − S. Repeated swaps reach the sorted order, so nothing beats it.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def solve(self, bt):
▶3 bt.sort()
▶4 clock = 0
▶5 total = 0
▶6 for t in bt:
▶7 total += clock
▶8 clock += t
▶9 return total // len(bt)
burst times43712cpu timelinenothing has run yetclock0total wait05 jobs, all ready at time 0
bt[4, 3, 7, 1, 2]burst time of each job
n5
Each tile is one job's burst time: how long it needs the CPU. Every job is ready at time 0, so the only question is the order. Each job that runs makes every job after it wait that much longer.
burst times, sorted12347cpu timelinenothing has run yetclock0total wait0sort: shortest job first
bt[1, 2, 3, 4, 7]ascending
Sort ascending. A short job at the front delays the others only a little; the longest job, 7, goes last, where it delays nobody. This order gives the smallest total wait.
burst times, sorted1wait 02347cpu timeline101clock1total wait0job 1 waits 0 · total 0
wait0time the CPU becomes free
total0
clock10 + 1
The shortest job, 1, starts at time 0, so it waits 0. Add the wait first, then move the clock forward by its burst: the clock is now 1.
burst times, sorted1wait 02wait 1347cpu timeline10213clock3total wait1job 2 waits 1 · total 1
wait1time the CPU becomes free
total1
clock31 + 2
Job 2 (burst 2) waited while every earlier job ran, so its wait is the clock, 1. Add it to the total (1), then advance the clock by 2 to 3. A job does not wait for its own run.
burst times, sorted1wait 02wait 13wait 347cpu timeline1021336clock6total wait4job 3 waits 3 · total 4
wait3time the CPU becomes free
total4
clock63 + 3
Job 3 (burst 3) waited while every earlier job ran, so its wait is the clock, 3. Add it to the total (4), then advance the clock by 3 to 6. A job does not wait for its own run.
burst times, sorted1wait 02wait 13wait 34wait 67cpu timeline1021334610clock10total wait10job 4 waits 6 · total 10
wait6time the CPU becomes free
total10
clock106 + 4
Job 4 (burst 4) waited while every earlier job ran, so its wait is the clock, 6. Add it to the total (10), then advance the clock by 4 to 10. A job does not wait for its own run.
burst times, sorted1wait 02wait 13wait 34wait 67wait 10cpu timeline1021334671017clock17total wait20job 5 waits 10 · total 20
wait10time the CPU becomes free
total20
clock1710 + 7
Job 5 (burst 7) waited while every earlier job ran, so its wait is the clock, 10. Add it to the total (20), then advance the clock by 7 to 17. A job does not wait for its own run.
burst times, sorted1wait 02wait 13wait 34wait 67wait 10cpu timeline1021334671017clock17total wait20average4total 20 / 5 → return 4
total20
return420 // 5 (rounded down)
The waits are 0, 1, 3, 6, 10, which add up to 20. The average is 20 / 5 = 4.
05

Common pitfalls

Counting a job's own run as waiting

✗ Wrong
clock += t
total += clock
✓ Right
total += clock
clock += t

Waiting time is the time before a job starts. Moving the clock first adds each job's own burst to its wait, which is the completion time, not the waiting time.

Forgetting to sort

✗ Wrong
for t in bt:  # input order
✓ Right
bt.sort()
for t in bt:

Running jobs in the given order is first-come, first-served. Its average is larger whenever a long job comes before a short one, and the sort is the entire SJF policy.

Keeping the total in a 32-bit int

✗ Wrong
int clock = 0, total = 0;
✓ Right
long long clock = 0, total = 0;

With 10⁵ jobs of length 10⁵, the clock reaches 10¹⁰ and the total about 5 × 10¹⁴. Both overflow an int in C++ and Java; Python integers do not overflow.

Rounding the average to the nearest integer

✗ Wrong
return round(total / len(bt))
✓ Right
return total // len(bt)

GFG wants the largest integer not above the average, so 4.6 must give 4. round gives 5, and floating-point division can also lose precision on totals this large.

06

Edge cases

One process, e.g. [5]

It starts at time 0, so its wait is 0 and the average is 0. The loop handles it with no special case.

07

Complexity

Time
O(n log n)
Space
O(1)
The sort dominates. The loop is O(n) with two counters; the sort itself may use O(log n) stack space.
08

This problem vs SJF with arrival times

A typical SJF program in OS courses, including GFG's article, handles processes that arrive at different times. That is a different, harder problem.

This problem (all ready at 0)Non-preemptive SJF with arrivalsPreemptive SJF (SRTF)
Which job runs nextthe next one in sorted orderthe shortest among jobs that have arrivedthe shortest remaining time, checked at every arrival
Toolone sortsort by arrival + min-heap by burstmin-heap, re-checked when a job arrives
CPU can sit idleneveryes, until the next arrivalyes, until the next arrival
Waiting timestart timestart time − arrivalfinish − arrival − burst
09

Shortest Job First FAQ

What are the steps?
  • Sort: sort the burst times in increasing order.
  • Sum: walk the sorted list; add the current clock to the total wait, then add the burst to the clock.
  • Answer: return total // n.
  • Complexity: O(n log n) time, O(1) extra space.
What changes when processes arrive at different times?

Sort by arrival time and keep a min-heap of the jobs that have arrived, keyed by burst. Each time the CPU is free, push every job that has arrived by now, then pop the shortest and run it. If the heap is empty, jump the clock to the next arrival. Waiting time becomes start time − arrival time. It is still O(n log n).

How are turnaround time and waiting time related?

Turnaround time is completion time − arrival time, and waiting time is turnaround time − burst time. With every process arriving at 0, turnaround equals completion time and waiting equals start time, which is why this solution only needs the clock.

Can you walk through an example by hand?

Take bursts [4, 3, 7, 1, 2]. Sorted: [1, 2, 3, 4, 7]. The jobs start at 0, 1, 3, 6 and 10, so those are their waits. The total is 20, and 20 / 5 = 4. In the given order instead, the waits would be 0, 4, 7, 14 and 15, an average of 8.