用c语言编程实现最短作业优先调度算法。
时间: 2024-05-02 13:21:10 浏览: 9
由于最短作业优先调度算法属于非抢占式调度算法,因此可以采用排序算法对作业进行排序,然后按照排好序的顺序依次执行作业。
下面是一个简单的C语言实现:
```c
#include <stdio.h>
#include <stdlib.h>
struct Process {
int id; // 进程ID
int arrive; // 到达时间
int burst; // 执行时间
int waiting; // 等待时间
int turnaround;// 周转时间
};
// 比较函数,用于排序
int cmp(const void *a, const void *b) {
const struct Process *p1 = (const struct Process *)a;
const struct Process *p2 = (const struct Process *)b;
return p1->burst - p2->burst;
}
int main() {
int n, i;
float avg_waiting = 0, avg_turnaround = 0;
printf("请输入进程数:");
scanf("%d", &n);
struct Process *p = (struct Process *)malloc(n * sizeof(struct Process));
for (i = 0; i < n; i++) {
printf("请输入第%d个进程的到达时间和执行时间:", i + 1);
scanf("%d%d", &p[i].arrive, &p[i].burst);
p[i].id = i + 1;
p[i].waiting = p[i].turnaround = 0;
}
// 按照执行时间排序
qsort(p, n, sizeof(struct Process), cmp);
// 计算等待时间和周转时间
int current_time = 0;
for (i = 0; i < n; i++) {
if (p[i].arrive > current_time) {
current_time = p[i].arrive;
}
p[i].waiting = current_time - p[i].arrive;
p[i].turnaround = p[i].burst + p[i].waiting;
current_time += p[i].burst;
avg_waiting += p[i].waiting;
avg_turnaround += p[i].turnaround;
}
// 输出结果
printf("进程ID\t到达时间\t执行时间\t等待时间\t周转时间\n");
for (i = 0; i < n; i++) {
printf("%d\t%d\t%d\t%d\t%d\n", p[i].id, p[i].arrive, p[i].burst, p[i].waiting, p[i].turnaround);
}
avg_waiting /= n;
avg_turnaround /= n;
printf("平均等待时间:%f\n", avg_waiting);
printf("平均周转时间:%f\n", avg_turnaround);
free(p);
return 0;
}
```
该程序首先读入进程数和各个进程的到达时间和执行时间,然后按照执行时间对进程进行排序,接着计算每个进程的等待时间和周转时间,并输出结果。最后计算平均等待时间和平均周转时间并输出。