输入N(N>0)个作业,输入每个作业的名字,到达时间,服务时间,按照短作业优先算法,计算每个作业的完成时间,周转时间,带权周转时间(保留2位小数)。
时间: 2024-05-23 08:09:24 浏览: 9
好的,我明白了您的问题。以下是您所需要的算法实现:
定义一个作业结构体,包含作业名、到达时间和服务时间。同时定义一个函数,用于比较两个作业的服务时间大小。
typedef struct {
char* name;
int arrive_time;
int service_time;
} Job;
int compare(Job* j1, Job* j2){
if (j1->service_time < j2->service_time) {
return -1;
} else if (j1->service_time > j2->service_time) {
return 1;
} else {
return 0;
}
}
接着,定义一个函数实现短作业优先算法。该函数输入一个作业数组和作业数目N,并计算每个作业的完成时间、周转时间和带权周转时间。
void sjf(Job* jobs, int N){
// 将所有作业按照到达时间排序
qsort(jobs, N, sizeof(Job), cmp_arrive_time);
int current_time = 0;
int sum_turnaround_time = 0;
int sum_weighted_turnaround_time = 0;
for (int i = 0; i < N; i++) {
// 找到在当前时间之前到达的所有作业中,服务时间最短的那一个
int shortest_job_index = -1;
int shortest_job_service_time = INT_MAX;
for (int j = 0; j < N; j++) {
if (jobs[j].arrive_time <= current_time && jobs[j].service_time < shortest_job_service_time) {
shortest_job_index = j;
shortest_job_service_time = jobs[j].service_time;
}
}
// 如果当前没有找到需要完成的作业,则将当前时间设置为下一个作业的到达时间
if (shortest_job_index == -1) {
current_time = jobs[i].arrive_time;
shortest_job_index = i;
}
// 计算三个指标
int completion_time = current_time + jobs[shortest_job_index].service_time;
int turnaround_time = completion_time - jobs[shortest_job_index].arrive_time;
int weighted_turnaround_time = turnaround_time / jobs[shortest_job_index].service_time;
// 更新总和
sum_turnaround_time += turnaround_time;
sum_weighted_turnaround_time += weighted_turnaround_time;
// 将当前时间设置成作业完成时间
current_time = completion_time;
// 交换当前作业和最短作业的位置,下一次开始搜索的位置往后移一位
swap(&jobs[i], &jobs[shortest_job_index]);
}
// 计算平均值
double average_turnaround_time = (double)sum_turnaround_time / N;
double average_weighted_turnaround_time = (double)sum_weighted_turnaround_time / N;
// 输出结果
for (int i = 0; i < N; i++) {
printf("Job %s completed at %d, turnaround time is %d, weighted turnaround time is %.2lf.\n", jobs[i].name, current_time, current_time - jobs[i].arrive_time, (double)(current_time - jobs[i].arrive_time) / jobs[i].service_time);
}
printf("Average turnaround time is %.2lf, average weighted turnaround time is %.2lf.\n", average_turnaround_time, average_weighted_turnaround_time);
}
以上就是您需要的算法实现,希望对您有所帮助。