0% found this document useful (0 votes)
14 views

SJF Scheduling Assignment Updated

Uploaded by

fantivostore
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

SJF Scheduling Assignment Updated

Uploaded by

fantivostore
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

REG. NO.

AP22110010136

NAME Saksham Saini

SUB. Operating Systems (CSE 302L)

DATE 19-09-2024

TOPIC SJF (Shortest Job First)

Question: What is SJF? Write its code in C/C++

Answer:

Shortest Job First (SJF) is a scheduling algorithm that assigns the CPU to the process with
the smallest burst time next. This method can be either preemptive or non-preemptive. In
non-preemptive SJF, the CPU is assigned to the shortest job, and it runs until it finishes.
Preemptive SJF, also known as Shortest Remaining Time First (SRTF), allows the currently
executing process to be preempted if a new process arrives with a shorter burst time. SJF
minimizes the average waiting time compared to other algorithms. However, it can lead to
starvation if shorter processes continuously enter the queue, preventing longer ones from
executing.

Code:

#include <iostream>
#include <algorithm>
using namespace std;

struct Process {
int pid;
int bt;
int wt;
int tat;
};

bool compare(Process a, Process b) {


return a.bt < b.bt;
}
int main() {
int n;
Process proc[10];

cout << "Enter number of processes: ";


cin >> n;

for (int i = 0; i < n; i++) {


proc[i].pid = i + 1;
cout << "Enter burst time of process " << i + 1 << ": ";
cin >> proc[i].bt;
}

sort(proc, proc + n, compare);

proc[0].wt = 0;
for (int i = 1; i < n; i++) {
proc[i].wt = proc[i - 1].wt + proc[i - 1].bt;
}

for (int i = 0; i < n; i++) {


proc[i].tat = proc[i].wt + proc[i].bt;
}

cout << "\nProcess\tBurst Time\tWaiting Time\tTurnaround Time\n";


for (int i = 0; i < n; i++) {
cout << "P" << proc[i].pid << "\t\t" << proc[i].bt << "\t\t"
<< proc[i].wt << "\t\t" << proc[i].tat << endl;
}

float avg_wt = 0, avg_tat = 0;


for (int i = 0; i < n; i++) {
avg_wt += proc[i].wt;
avg_tat += proc[i].tat;
}

cout << "\nAverage Waiting Time: " << avg_wt / n << endl;
cout << "Average Turnaround Time: " << avg_tat / n << endl;

return 0;
}

Sample Output:
Enter number of processes: 3
Enter burst time of process 1: 6
Enter burst time of process 2: 8
Enter burst time of process 3: 7

Process Burst Time Waiting Time Turnaround Time


P1 6 0 6
P3 7 6 13
P2 8 13 21

Average Waiting Time: 6.33333


Average Turnaround Time: 13.3333

You might also like