SJF短作业优先(非抢占式)算法C++代码实现

SJF短作业优先(非抢占式)算法C++代码实现,第1张

SJF短作业优先(非抢占式)算法C++代码实现
#include 
#include 
#include 
using namespace std;

const int MAX_PROCESS = 20;//进程最大数量
int processnum;//进程数量
bool isArrived[MAX_PROCESS];//标记是否到达


struct Process
{
	int hour, minute;//到达时间(8:00)
	int arrive, work, turn;//到达时间,执行时间,周转时间
	double weightturn;//带权周转时间
	int id;//进程序号
}process[MAX_PROCESS];

bool cmparr(Process p1, Process p2)
{
	return p1.arrive < p2.arrive;
}

bool cmpwork(Process p1, Process p2)
{
	return p1.work < p2.work;
}

void SJF()
{
	deque Q;
	Process st[MAX_PROCESS];//进程执行顺序
	sort(process + 1, process + processnum + 1, cmparr);
	int first = process[1].arrive;
	for (int i = 1; i <= processnum; i++) process[i].arrive -= first;
	Q.push_back(process[1]);//将第一个到达的进程入队
	isArrived[1] = true;
	int idx = 1;
	while (process[++idx].arrive == process[idx - 1].arrive)
	{
		Q.push_back(process[idx]);//将与第一个进程同时到达的也入队
		isArrived[idx] = true;
	}
	int time = 0;//总执行时间(分)
	int finish = 0;//执行完成数量
	while (finish < processnum)
	{
		sort(Q.begin(), Q.end(), cmpwork);//将进程按执行时间从小到大排序
		auto x = Q.front();//取出执行时间最短的上处理机运行
		Q.pop_front();
		time += x.work;
		x.turn = time - x.arrive;
		x.weightturn = (double)x.turn / x.work;
		st[++finish] = x;
		for(int i = 1; i <= processnum; i++)
			if (!isArrived[i] && process[i].arrive <= time)//如果进程已到达但还没入队
			{
				Q.push_back(process[i]);
				isArrived[i] = true;
			}
	}
	cout << endl << "执行序列 : ";
	for (int i = 1; i <= finish; i++)
	{
		cout << st[i].id;
		if (i != finish) cout << " -> ";
	}
	cout << endl;
	cout << endl << "周转时间 : ";
	for (int i = 1; i <= processnum; i++)
		cout << "进程" << st[i].id << " : " << st[i].turn << "   ";
	cout << endl;
	cout << endl << "带权周转时间 : ";
	for (int i = 1; i <= processnum; i++)
		cout << "进程" << st[i].id << " : " << st[i].weightturn << "   ";
	cout << endl;
	cout << endl << "平均周转时间 : ";
	double avgturn = 0;
	for (int i = 1; i <= processnum; i++)
		avgturn += st[i].turn;
	cout << avgturn / processnum;
	cout << endl;
	cout << endl << "平均带权周转时间 : ";
	double avgweightturn = 0;
	for (int i = 1; i <= processnum; i++)
		avgweightturn += st[i].weightturn;
	cout << avgweightturn / processnum;
	cout << endl;
}

int main()
{
	printf("请输入进程数量 : ");
	scanf("%d", &processnum);
	for (int i = 1; i <= processnum; i++)
	{
		printf("请输入进程%d的到达时间、执行时间 : ", i);
		scanf("%d:%d %d", &process[i].hour, &process[i].minute, &process[i].work);
		process[i].arrive = process[i].hour * 60 + process[i].minute;
		process[i].id = i;
	}
	SJF();
	return 0;
}

运行结果图

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/3970218.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-10-21
下一篇 2022-10-21

发表评论

登录后才能评论

评论列表(0条)

保存