C++ Program for Preemptive SJF (Shortest Job First)

0

 


#include <bits/stdc++.h>
using namespace std;

struct Process {
  int pid;
  int burst_time;
  int wait_time;
  int turnaround_time;
};

bool compare(Process a, Process b) {
  return a.burst_time < b.burst_time;
}

int main() {
  int n;
  cout << "Enter the number of processes: ";
  cin >> n;

  Process p[n];
  for (int i = 0; i < n; i++) {
    p[i].pid = i + 1;
    cout << "Enter the burst time of process " << i + 1 << ": ";
    cin >> p[i].burst_time;
  }

  sort(p, p + n, compare);

  p[0].wait_time = 0;
  for (int i = 1; i < n; i++) {
    p[i].wait_time = p[i - 1].wait_time + p[i - 1].burst_time;
  }

  for (int i = 0; i < n; i++) {
    p[i].turnaround_time = p[i].burst_time + p[i].wait_time;
  }

  cout << "Process ID\tBurst Time\tWait Time\tTurnaround Time\n";
  for (int i = 0; i < n; i++) {
    cout << p[i].pid << "\t\t" << p[i].burst_time << "\t\t" << p[i].wait_time << "\t\t" << p[i].turnaround_time << endl;
  }

  return 0;
}

Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !