The Shortest Job First, or SJF algorithm allocates the CPU to the next process that requires the shortest length of time to complete. In the case of more than one process having the same time required, the FCFS algorithm is used to "break" the tie. Since SJF reduces the average waiting time of processes, it is considered optimal.
The SJF algorithm can be either preemptive or non-preemptive. In a preemptive SJF system, if a newly arrived process has a shorter time to complete, the system may preempt the currently executing process. Preemptive SJF scheduling is sometimes called Shortest-Remaining-Time-First scheduling.
In a non-preemptive SJF implementation, the CPU will run a process to completion, before picking the next shortest process from the queue. In Fig. SFJ-1, Process A arrives first and starts execution. While the CPU executes Process A, Process B, C and D arrives in that order. Because Process D takes the least amount of CPU-burst time, the scheduler selects it after Process A completes.

Fig. SJF-1
For a preemptive SJF first (or Shortest-Remaining-Time-First) system, the scheduler suspends a running process whenever there is a process that requires a shorted CPU-burst time available. In Fig. SJF-2, Process A requires 9 units of time, and arrives first. While is executes, Process B, which requires only 5 units of time, arrives. The scheduler preempts Process A and gives the CPU to Process B, since Process B has a shorter CPU-burst time. Halfway through Process B's execution, Process C and D arrive at the same time. Because Process D only requires 3 units of time, the scheduler suspends Process B's execution and gives the CPU to process D instead. After D completes, Process B, which has the next shortest CPU-burst time, runs again.

Fig. SJF-2
The real difficulty with the SJF algorithm is knowing the length of the waiting CPU requests. Systems that use SJF normally store an average of the process times that were encountered in the past. As such, SJF is useful mostly in long-term scheduling, and is almost impossible to implement at the level of short-term CPU scheduling.