Scheduling problems
Intermediate · 10 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Scheduling problems ask in what order to run jobs on one machine to get a good outcome, such as the lowest average waiting time. The surprising greedy rule is that running the shortest jobs first keeps everyone's waiting low.
Practical use cases
- Web app: Running quick print jobs before big ones. A print shop site has one printer queue. A 2-page flyer stuck behind a 500-page book waits ages. Putting short jobs first lowers the average wait for customers, and the big job only waits a little longer. Most customers walk away happier, which is why shops quietly use this rule.
- Web app: Background job queue. A Laravel queue has quick email jobs and slow report exports. Running quick ones first keeps notifications feeling instant while exports still finish soon after.
- Web app: Delivery batches. A delivery app has orders with different preparation times. Starting the quick ones first sends more customers their food earlier, and average waiting drops. Fewer customers cancel and kitchen ratings improve even though total cooking time is the same.
- System: CPU schedulers and factory floors. Operating systems prefer short tasks to keep the machine responsive, and factory planners sequence quick jobs first to cut work in progress. In every setting the idea is that a quick job barely delays a long one, but a long job in front of many quick ones delays all of them.
The story: The Slow Bill at the Kirana Counter
On Sunday evening the kirana store was packed. Four customers waited at the single billing counter: a big monthly shopping list of 8 minutes, a medium one of 7, and two smaller ones of 6 and 3 minutes. The owner, Mr. Gupta, served them in the order they came. The 3-minute customer, last in line, waited 21 minutes just to buy two biscuit packets!
Mira was sitting on a sack of rice and whispered: "Serve the quick ones first. Each person waits for everybody ahead of them, so a long job at the front makes everyone behind wait longer." Sorted from shortest to longest, the total waiting dropped from 41 to 28 minutes.
Mr. Gupta nodded and then asked about something different: "I also have jobs with promised delivery days. Which should I do first?" Mrs. Sharma's answer: it depends on what you want to improve. For the average waiting time, go shortest job first. To avoid missing deadlines, go earliest deadline first. To fit the most jobs into one room, go earliest finish first.
This is the heart of scheduling problems: all of them are solved by sorting by the right key, then picking in order. The sorting key changes with the goal, and picking the wrong key quietly gives wrong answers. Greedy works here because swapping two neighbours that are in the wrong order can only improve things.
How to spot this problem, and where you need it
Users complain that simple requests wait a long time behind big ones in the same queue, and you want to reduce the average waiting time for everybody.
Signs you need it
- One machine, worker or queue handles jobs of very different sizes in the order they arrived.
- The wording is "minimise total or average waiting time", "turnaround time" or "completion time".
- A small job behind a huge one makes the whole line feel slow.
Where to use it in a project
- Job queues, print servers and export workers handling mixed small and large tasks.
- Kitchen, delivery and support-desk ordering where quick items can go first.
The solution
Sort the jobs by length, shortest first, and run them in that order. Each job's waiting time is the sum of the lengths before it, so putting short ones early makes that sum small for many jobs, while the one long job only adds its own length to itself. For deadlines or priorities, adjust the sorting key, for example by deadline or by value per minute.
Payoff: Before: average wait of 40 minutes in arrival order. After: about 12 minutes with shortest-first, with the same total work.
Explain it like I am 8
If you have to give out balloons and some kids take a long time to choose, let the quick choosers go first. Then more kids are happy sooner, and the slow chooser only delays themselves, not the whole line.
How it works, step by step
- Decide the goal: lowest average waiting time? fewest late jobs? most jobs done?
- Pick the matching sort key: shortest duration, earliest deadline, or earliest finish.
- Sort the jobs by that key.
- Run the jobs in that order, adding up each job's waiting time as the sum of the jobs before it.
- If two neighbours are in the wrong order, swapping them would help. A sorted order has no such pair left.
The code in four languages
PHP
<?php
// Average waiting time when jobs run one after another in the given order.
function averageWait(array $durations): float {
$wait = 0; // how long the current job has waited
$total = 0;
foreach ($durations as $d) {
$total += $wait; // this job waited for everyone before it
$wait += $d;
}
return $total / count($durations);
}
$bills = [6, 8, 7, 3]; // minutes per customer, arrival order
$sorted = $bills;
sort($sorted); // greedy: shortest job first
echo "Arrival order : " . averageWait($bills) . PHP_EOL; // 10.25
echo "Shortest first: " . averageWait($sorted) . PHP_EOL; // 7JavaScript
// Average waiting time when jobs run one after another in the given order.
function averageWait(durations) {
let wait = 0; // how long the current job has waited
let total = 0;
for (const d of durations) {
total += wait; // this job waited for everyone before it
wait += d;
}
return total / durations.length;
}
const bills = [6, 8, 7, 3]; // minutes per customer, arrival order
const sorted = [...bills].sort((a, b) => a - b); // greedy: shortest job first
console.log("Arrival order : " + averageWait(bills)); // 10.25
console.log("Shortest first: " + averageWait(sorted)); // 7Java
import java.util.*;
public class Main {
// Average waiting time when jobs run one after another in the given order.
static double averageWait(int[] durations) {
int wait = 0; // how long the current job has waited
int total = 0;
for (int d : durations) {
total += wait; // this job waited for everyone before it
wait += d;
}
return (double) total / durations.length;
}
public static void main(String[] args) {
int[] bills = {6, 8, 7, 3}; // minutes per customer, arrival order
int[] sorted = bills.clone();
Arrays.sort(sorted); // greedy: shortest job first
System.out.println("Arrival order : " + averageWait(bills)); // 10.25
System.out.println("Shortest first: " + averageWait(sorted)); // 7.0
}
}Go
package main
import (
"fmt"
"slices"
)
// averageWait is the average waiting time when jobs run one after another in the given order.
func averageWait(durations []int) float64 {
wait := 0 // how long the current job has waited
total := 0
for _, d := range durations {
total += wait // this job waited for everyone before it
wait += d
}
return float64(total) / float64(len(durations))
}
func main() {
bills := []int{6, 8, 7, 3} // minutes per customer, arrival order
sorted := slices.Clone(bills)
slices.Sort(sorted) // greedy: shortest job first
fmt.Println("Arrival order :", averageWait(bills)) // 10.25
fmt.Println("Shortest first:", averageWait(sorted)) // 7
}Time: O(n log n) · Extra space: O(n). The only real work is sorting by the chosen rule; adding up the waiting times is one pass.
Watch out for
- Using one rule for every goal. "Shortest first" minimises average waiting but may make long jobs wait forever (starvation) and does not help with deadlines.
- Forgetting that a job's waiting time is the sum of the jobs before it, not including itself.
- Sorting in place and losing the original order you still need to report.
Quick check
- Which order gives the smallest average waiting time?
- Shortest job first
- Longest job first
- Arrival order
- If the goal is to finish as many jobs as possible on one machine with start and end times, which rule works?
- Shortest duration first
- Latest start first
- Earliest finish first
- What is a risk of always serving the shortest job first?
- It uses too much memory
- Long jobs may wait a very long time
- The average wait gets bigger