PRIORITY SCHEDULING NON-PREEMPTIVE
#include <iostream>
#include <algorithm>
#include <iomanip>
#include <climits>
using namespace std;
struct Process {
int id, arrival,burst,priority,start,completion,turnaround,waiting;
bool completed = false; };
int main() {
int n;
cout << "Enter number of processes: ";
cin >> n;
Process p[n];
for (int i = 0; i < n; i++) {
p[i].id = i + 1;
cout << "Enter arrival time for Process P" << p[i].id << ": ";
cin >> p[i].arrival;
cout << "Enter burst time for Process P" << p[i].id << ": ";
cin >> p[i].burst;
cout << "Enter priority for Process P" << p[i].id << " (lower number = higher
priority): ";
cin >> p[i].priority;}
float completed =0, currentTime =0, totalTAT =0, totalWT = 0;
while (completed < n) {
int idx = -1;
int bestPrio = INT_MAX;
for (int i = 0; i < n; i++) {
if (!p[i].completed && p[i].arrival <= currentTime) {
if (p[i].priority < bestPrio) {
bestPrio = p[i].priority;
idx = i;
} else if (p[i].priority == bestPrio&& p[i].arrival < p[idx].arrival){
idx = i;}}}
if (idx == -1) {
currentTime++;
} else {
p[idx].start = currentTime;
p[idx].completion = p[idx].start + p[idx].burst;
p[idx].turnaround = p[idx].completion - p[idx].arrival;
p[idx].waiting = p[idx].turnaround - p[idx].burst;
p[idx].completed = true;
currentTime = p[idx].completion;
totalTAT += p[idx].turnaround;
totalWT += p[idx].waiting;
completed++;}}
cout << "\nPID\tAT\tBT\tPR\tST\tCT\tTAT\tWT\n";
for (int i = 0; i < n; i++) {
cout<<"P"<<p[i].id<<"\t"<<p[i].arrival<<"\t"<<p[i].burst<<"\t"<<p[i].priority<<"\t"<<p
[i].start<< "\t"<<p[i].completion<< "\t"<<p[i].turnaround<< "\t"<<p[i].waiting<<"\n";}
cout << "Gantt Chart:\n";
cout << " ";
for (int i = 0; i < n; i++)
cout << "-------";
cout << "\n|";
sort(p, p + n, [](const Process &a, const Process &b) {
return a.start < b.start;});
for (int i = 0; i < n; i++) {
cout << " P" << p[i].id << " |";}
cout << "\n ";
for (int i = 0; i < n; i++) cout << "-------";
cout << "\n" << p[0].start;
for (int i = 0; i < n; i++) {
cout << setw(7) << p[i].completion;}
cout << "\nAverage Turnaround Time: " << (totalTAT / n);
cout << "\nAverage Waiting Time: " << (totalWT / n) << "\n";
return 0;}