712538. Shortest Job first

Medium

Shortest Job First

Summary

The Shortest Job First (SJF) scheduling algorithm is a method used to allocate tasks or jobs to processors in a computer system. The key concept involved is the priority of each job, which is determined by its burst time. The algorithm assigns the shortest job first, and then the next shortest job until all jobs are completed.

Detailed Explanation

To understand the SJF scheduling algorithm, let's consider an example. Suppose we have three jobs A, B, and C with burst times 3, 2, and 1 units respectively. The algorithm would work as follows:

  1. Find the shortest job: In this case, it is Job C with a burst time of 1 unit.
  2. Execute Job C: Since its burst time is 1 unit, it will be executed for 1 unit of time.
  3. Update the available time: After executing Job C, the available time becomes 3 units (4 - 1).
  4. Find the next shortest job: Among Jobs A and B, Job B has a shorter burst time (2 units) than Job A (3 units). So, Job B is selected for execution.
  5. Execute Job B: Since its burst time is 2 units, it will be executed for 2 units of time.
  6. Update the available time: After executing Job B, the available time becomes 1 unit (3 - 2).
  7. Find the next shortest job: Among Jobs A and C, Job C has a shorter burst time (1 unit) than Job A (3 units). So, Job C is selected for execution.
  8. Execute Job A: Since its burst time is 3 units, it will be executed for 3 units of time.
  9. The algorithm terminates after all jobs are completed.

Time Complexity Analysis: The SJF scheduling algorithm has a time complexity of O(n), where n is the number of jobs.

Space Complexity Analysis: The SJF scheduling algorithm requires O(1) space to store the available time and job information.

Optimized Solutions

Java

View on GeeksforGeeks
public class ShortestJobFirst {
    public static void sjf(int[] burstTimes) {
        int minTime = 0;
        for (int time : burstTimes) {
            if (time < minTime) {
                minTime = time;
            }
        }
        System.out.println("Shortest Job First: " + minTime);
    }

    public static void main(String[] args) {
        int[] burstTimes = {3, 2, 1};
        sjf(burstTimes);
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.