710290. Calculate the average Waiting Time and Turnaround Time using Shortest Job First
Medium
Here is a detailed Markdown blog post for the GeeksforGeeks problem:
Calculate the average Waiting Time and Turnaround Time using Shortest Job First
Slug: calculate-the-average-waiting-time-and-turnaround-time-using-shortest-job-first
Difficulty: Medium
Id: 710290
Summary
The Shortest Job First (SJF) scheduling algorithm prioritizes the shortest job in the ready queue for execution. This problem requires calculating the average waiting time and turnaround time of a set of jobs scheduled using SJF.
Detailed Explanation
To calculate the average waiting time and turnaround time, we need to first schedule the jobs using the SJF algorithm. The algorithm works by selecting the shortest job from the ready queue and executing it until its completion.
Here's a step-by-step breakdown of the solution:
- Initialize variables:
nis the number of jobs,t_arr[i]is the arrival time of jobi,t_burst[i]is the burst time (execution time) of jobi, andw_time[i]andt_turn[i]are the waiting time and turnaround time for jobi, respectively. - Calculate the total waiting time (
total_w_time) and turnaround time (total_t_turn). - Sort the jobs by their arrival times and then by their burst times (in ascending order). This is the ready queue.
- Initialize the current time (
curr_time) to 0. - Iterate through the ready queue:
- For each job
i, calculate its waiting timew_time[i]as the difference between its arrival timet_arr[i]and the current timecurr_time. - Calculate its turnaround time
t_turn[i]as the sum of its waiting timew_time[i]and its burst timet_burst[i]. - Update the current time (
curr_time) to be the completion time of jobi, which is the sum of its arrival time and its burst time.
- For each job
- Calculate the average waiting time (
avg_w_time) as the total waiting time (total_w_time) divided by the number of jobs (n). - Calculate the average turnaround time (
avg_t_turn) as the total turnaround time (total_t_turn) divided by the number of jobs (n).
Optimized Solutions
Java
public class SJFScheduling {
public static void main(String[] args) {
int n = 5; // number of jobs
int[] t_arr = {0, 1, 2, 4, 6}; // arrival times
int[] t_burst = {3, 2, 7, 1, 4}; // burst times
int total_w_time = 0;
int total_t_turn = 0;
for (int i = 0; i < n; i++) {
int w_time = t_arr[i] + t_burst[i];
int t_turn = w_time + t_burst[i];
total_w_time += w_time;
total_t_turn += t_turn;
}
double avg_w_time = (double) total_w_time / n;
double avg_t_turn = (double) total_t_turn / n;
System.out.println("Average waiting time: " + avg_w_time);
System.out.println("Average turnaround time: " + avg_t_turn);
}
}