-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpriority.cpp
More file actions
86 lines (75 loc) · 2.23 KB
/
priority.cpp
File metadata and controls
86 lines (75 loc) · 2.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/*
Title: Priority CPU Scheduling
Description: Non-preemptive priority scheduling with Gantt chart and time display.
Time Complexity: O(n²)
Space Complexity: O(n)
*/
#include <iostream>
#include <vector>
#include <climits>
using namespace std;
struct Process {
int pid, at, bt, priority;
};
void printGanttChart(const vector<int> &gantt, const vector<int> &time) {
cout << "\nGantt Chart:\n ";
for (int pid : gantt)
cout << "| P" << pid << " ";
cout << "|\n";
cout << time[0];
for (int i = 1; i < (int)time.size(); i++)
cout << " " << time[i];
cout << "\n";
}
int main() {
int n;
cout << "Enter number of processes: ";
cin >> n;
vector<Process> p(n);
for (int i = 0; i < n; i++) {
p[i].pid = i + 1;
cout << "\nEnter details for Process " << i + 1 << "\n";
cout << "Arrival Time: ";
cin >> p[i].at;
cout << "Burst Time: ";
cin >> p[i].bt;
cout << "Priority (Lower number = Higher priority): ";
cin >> p[i].priority;
}
vector<int> wt(n), tat(n), gantt, time(1, 0);
vector<bool> done(n, false);
int completed = 0, t = 0;
float totalWT = 0, totalTAT = 0;
while (completed < n) {
int idx = -1, minP = INT_MAX;
for (int i = 0; i < n; i++) {
if (!done[i] && p[i].at <= t && p[i].priority < minP) {
minP = p[i].priority;
idx = i;
}
}
if (idx == -1) {
t++;
continue;
}
gantt.push_back(p[idx].pid);
t += p[idx].bt;
time.push_back(t);
tat[idx] = t - p[idx].at;
wt[idx] = tat[idx] - p[idx].bt;
done[idx] = true;
completed++;
}
cout << "\n--- Priority Scheduling ---\n";
cout << "PID\tAT\tBT\tPRIO\tWT\tTAT\n";
for (int i = 0; i < n; i++) {
cout << "P" << p[i].pid << "\t" << p[i].at << "\t" << p[i].bt
<< "\t" << p[i].priority << "\t" << wt[i] << "\t" << tat[i] << "\n";
totalWT += wt[i];
totalTAT += tat[i];
}
cout << "Average Waiting Time = " << totalWT / n << "\n";
cout << "Average Turnaround Time = " << totalTAT / n << "\n";
printGanttChart(gantt, time);
return 0;
}