假设磁盘共有200个柱面,编号为0~199。刚刚处理访问了78号柱面的请求,当前存取臀正在60号柱面上服务。现有若干请求者要访问的柱面号分别为:50、92、120、30、65、100、130。按下列三种算法调度时,实际服务的次序是什么?存取臀移动总量为多少?(1)先来先服务;(2)最短查找时间优先;(3)电梯调度算法 用++写代码实现这三种算法
时间: 2024-02-19 07:03:12 浏览: 189
好的,以下是用C++实现这三种算法的代码:
1. 先来先服务算法(FCFS):
```cpp
#include <iostream>
#include <queue>
#include <cmath>
using namespace std;
int main() {
int n = 7; // 请求个数
int cur_pos = 60; // 当前磁头位置
int request[] = {50, 92, 120, 30, 65, 100, 130}; // 请求队列
queue<int> q;
for (int i = 0; i < n; i++) {
q.push(request[i]);
}
int total_distance = 0;
while (!q.empty()) {
int next_pos = q.front();
q.pop();
total_distance += abs(next_pos - cur_pos);
cur_pos = next_pos;
cout << cur_pos << " ";
}
cout << endl << "Total distance: " << total_distance << endl;
return 0;
}
```
2. 最短查找时间优先算法(SSTF):
```cpp
#include <iostream>
#include <queue>
#include <cmath>
using namespace std;
int main() {
int n = 7; // 请求个数
int cur_pos = 60; // 当前磁头位置
int request[] = {50, 92, 120, 30, 65, 100, 130}; // 请求队列
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
for (int i = 0; i < n; i++) {
pq.push(make_pair(abs(request[i] - cur_pos), request[i]));
}
int total_distance = 0;
while (!pq.empty()) {
int next_pos = pq.top().second;
pq.pop();
total_distance += abs(next_pos - cur_pos);
cur_pos = next_pos;
cout << cur_pos << " ";
}
cout << endl << "Total distance: " << total_distance << endl;
return 0;
}
```
3. 电梯调度算法(SCAN):
```cpp
#include <iostream>
#include <queue>
#include <cmath>
using namespace std;
int main() {
int n = 7; // 请求个数
int cur_pos = 60; // 当前磁头位置
int request[] = {50, 92, 120, 30, 65, 100, 130}; // 请求队列
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq1, pq2;
for (int i = 0; i < n; i++) {
if (request[i] >= cur_pos) {
pq1.push(make_pair(request[i], abs(request[i] - cur_pos)));
} else {
pq2.push(make_pair(request[i], abs(request[i] - cur_pos)));
}
}
int total_distance = 0;
while (!pq1.empty()) {
int next_pos = pq1.top().first;
pq1.pop();
total_distance += abs(next_pos - cur_pos);
cur_pos = next_pos;
cout << cur_pos << " ";
}
while (!pq2.empty()) {
int next_pos = pq2.top().first;
pq2.pop();
total_distance += abs(next_pos - cur_pos);
cur_pos = next_pos;
cout << cur_pos << " ";
}
cout << endl << "Total distance: " << total_distance << endl;
return 0;
}
```
希望能够帮助你!
阅读全文