Written by Sai Sandeep Thota on September 2, 2013 in Java > Programming

Java Program to implement Shortest Job First (SJF)


Get our Latest updates delivered to your mailbox!

Process Scheduling algorithms are used to execute Processes in the queue within minimal time. Here we wrote Java Program to implement Shortest Job First (SJF). There are 4 Process scheduling algorithms. Shortest Job First Algorithm is one among them, It sorts the processes based on their burst time. The Process which is having the lowest burst time is executed first.

Q: What is Burst Time?
A: In simple words, Burst time is the time required to complete the execution of a Process.

What we are doing in this program? First we populate two arrays process[] – stores process ID’s and ptime[] – stores process burst times. We are using two for loops to sort processes in ascending order based on their burst time and then calculate waiting time and total time. Finally we print the sorted Processes.

You may also consider:

Shortest Job First Java Program

import java.util.Scanner;

class sjf {
	public static void main(String args[])
		int process[] = new int[10];
		int ptime[] = new int[10];
		int wtime[] = new int[10];
		int temp, n, total=0;
		float avg=0;
		Scanner get = new Scanner(System.in);

		System.out.println("Enter Number of Processes:");
		n = get.nextInt();
		for(int i=0;i<n;i++)
			System.out.println("Enter Process "+(i+1)+" ID: ");
			process[i] = get.nextInt();
			System.out.println("Enter Process "+(i+1)+" Burst Time: ");
			ptime[i] = get.nextInt();

		for(int i=0;i<n-1;i++)
			for(int j=i+1;j<n;j++) 			{ 				if(ptime[i]>ptime[j])
					temp = ptime[i];
					ptime[i] = ptime[j];
					ptime[j] = temp;
					temp = process[i];
					process[i] = process[j];
					process[j] = temp;

		wtime[0] = 0;
		for(int i=1;i<n;i++)
			wtime[i] = wtime[i-1]+ptime[i-1];
			total = total + wtime[i];
		avg = (float)total/n;
		System.out.println("P_ID P_TIME W_TIME");
		for(int i=0;i<n;i++)
		System.out.println("Total Waiting Time: "+total);
		System.out.println("Average Waiting Time: "+avg);

Download Source Code

Shortest Job First Java Program Output

{ 1 comment… read it below or add one }

gayathri January 17, 2014 at 11:44 pm

hai u please explain sjf program in {programming unit}


Leave a Comment

Previous post:

Next post: