生成一段在先来先服务基础上进行短作业优先的排序的c语言代码
时间: 2024-05-19 21:17:44 浏览: 51
以下是一段在先来先服务基础上进行短作业优先的排序的C语言代码:
#include <stdio.h>
struct process {
int pid;
int arrival_time;
int burst_time;
int waiting_time;
int turnaround_time;
};
void sort_processes(struct process *processes, int num_processes) {
int i, j;
struct process temp;
for (i = 0; i < num_processes - 1; ++i) {
for (j = i + 1; j < num_processes; ++j) {
if (processes[i].arrival_time > processes[j].arrival_time) {
temp = processes[i];
processes[i] = processes[j];
processes[j] = temp;
}
}
}
}
int main() {
int num_processes, i, j;
struct process processes[100], temp;
float avg_waiting_time = 0.0, avg_turnaround_time = 0.0;
printf("Enter the number of processes: ");
scanf("%d", &num_processes);
printf("Enter the arrival time and burst time of each process:\n");
for (i = 0; i < num_processes; ++i) {
printf("Process %d: ", i + 1);
scanf("%d %d", &processes[i].arrival_time, &processes[i].burst_time);
processes[i].pid = i + 1;
}
sort_processes(processes, num_processes);
int current_time = 0;
for (i = 0; i < num_processes; ++i) {
for (j = i + 1; j < num_processes; ++j) {
if (processes[j].arrival_time > current_time) {
break;
}
if (processes[i].burst_time > processes[j].burst_time) {
temp = processes[i];
processes[i] = processes[j];
processes[j] = temp;
}
}
current_time += processes[i].burst_time;
processes[i].turnaround_time = current_time - processes[i].arrival_time;
processes[i].waiting_time = processes[i].turnaround_time - processes[i].burst_time;
}
printf("PID\tARRIVAL TIME\tBURST TIME\tWAITING TIME\tTURNAROUND TIME\n");
for (i = 0; i < num_processes; ++i) {
printf("%d\t%d\t\t%d\t\t%d\t\t%d\n", processes[i].pid, processes[i].arrival_time, processes[i].burst_time, processes[i].waiting_time, processes[i].turnaround_time);
avg_waiting_time += processes[i].waiting_time;
avg_turnaround_time += processes[i].turnaround_time;
}
avg_waiting_time /= num_processes;
avg_turnaround_time /= num_processes;
printf("Average waiting time: %.2f units\n", avg_waiting_time);
printf("Average turnaround time: %.2f units\n", avg_turnaround_time);
return 0;
}
阅读全文