-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSJF.c
71 lines (60 loc) · 1.79 KB
/
SJF.c
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
#include <stdio.h>
int main() {
int bt[20], tat[20], wt[20], p[20];
int total = 0, n, pos, temp;
float avtat, avwt;
printf("Enter the number of processes: ");
if (scanf("%d", &n) != 1 || n <= 0) {
printf("Invalid number of processes.\n");
return 1;
}
printf("Enter the burst times for each process:\n");
for (int i = 0; i < n; i++) {
printf("P[%d]: ", i + 1);
if (scanf("%d", &bt[i]) != 1 || bt[i] < 0) {
printf("Invalid burst time.\n");
return 1;
}
p[i] = i + 1; // Initialize process IDs
}
// Sorting based on burst time (SJF Scheduling)
for (int i = 0; i < n - 1; i++) {
pos = i;
for (int j = i + 1; j < n; j++) {
if (bt[j] < bt[pos]) {
pos = j;
}
}
// Swap burst times
temp = bt[i];
bt[i] = bt[pos];
bt[pos] = temp;
// Swap process IDs
temp = p[i];
p[i] = p[pos];
p[pos] = temp;
}
// Waiting time calculation
wt[0] = 0; // First process has no waiting time
total = 0;
for (int i = 1; i < n; i++) {
wt[i] = bt[i - 1] + wt[i - 1];
total += wt[i];
}
avwt = (float)total / n; // Average waiting time
// Turnaround time calculation
total = 0;
for (int i = 0; i < n; i++) {
tat[i] = wt[i] + bt[i];
total += tat[i];
}
avtat = (float)total / n; // Average turnaround time
// Print results
printf("\nProcess\t\tBurst Time\tWaiting Time\tTurnaround Time\n");
for (int i = 0; i < n; i++) {
printf("P[%d]\t\t%d\t\t%d\t\t%d\n", p[i], bt[i], wt[i], tat[i]);
}
printf("\nAverage Waiting Time: %.2f\n", avwt);
printf("Average Turnaround Time: %.2f\n", avtat);
return 0;
}