Job scheduling: keep the total waiting as small as possible
One server, four jobs. Serve the shortest job first, because everyone behind a job has to wait for it.Order 1 → 2 → 5 → 10Total 46Average 11.5GreedyO(n log n)Picture one photocopy machine and four people in line, needing 3, 7, 4 and 8 minutes. If the 8-minute person goes first, all three others wait those 8 minutes. If the 3-minute person goes first, the others wait only 3. Short jobs first means less waiting for everyone.
See it: switch the order and watch the waiting
Time in system = 3 + 7 + 14 + 22 = 46 · total waiting 24
Time in system = 3 + 10 + 14 + 22 = 49 · total waiting 27
Time in system = 8 + 15 + 19 + 22 = 64 · total waiting 42
How the program works
- Store each job's number and service time in a struct.
- Sort the jobs by service time, smallest first (the greedy choice). The program uses insertion sort.
- Walk through the sorted jobs, keeping a running clock. Each job's finish time is its time in the system.
- Add up the finish times: 3 + 7 + 14 + 22 = 46, and divide by 4 for the average, 11.5.
Show the program and what each part does
struct job { int id; int service; };
/* insertion sort: each job slides left past longer jobs */
void sort_by_service(struct job a[], int n) {
int i, j; struct job key;
for (i = 1; i < n; i++) {
key = a[i]; j = i - 1;
while (j >= 0 && a[j].service > key.service) {
a[j + 1] = a[j]; j--;
}
a[j + 1] = key;
}
}
int main(void) {
struct job jobs[] = { {1,3}, {5,7}, {2,4}, {10,8} };
int n = sizeof(jobs) / sizeof(jobs[0]);
int i, finish = 0, total = 0;
sort_by_service(jobs, n);
for (i = 0; i < n; i++) {
finish += jobs[i].service; /* this job leaves now */
total += finish;
}
printf("Total = %d, Average = %.2f\n", total, (float) total / n);
return 0;
}sizeof(jobs)/sizeof(jobs[0])- Bytes of the whole array ÷ bytes of one job = the number of jobs, 4.
finish += …- The running clock: each job leaves when its own service ends.
(float) total / n- A type cast, so 46 / 4 gives 11.50 instead of 11.
There is one server and four jobs. A job's time in the system is when it finishes. Since every job waits for the ones ahead of it, I used the greedy rule of shortest service time first. I sort by service time with insertion sort and add up the finishing times. The order is 1, 2, 5, 10 with a total of 46, which is the minimum: the order as given gives 49, and longest first gives 64. With a proper sort it is O(n log n).

