磁盘调度算法c++代码
时间: 2024-01-07 11:22:41 浏览: 84
以下是一个使用C++实现的磁盘调度算法的示例代码:
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// FCFS算法
int fcfs(vector<int>& requests, int start) {
int total_distance = 0;
int current_track = start;
for (int i = 0; i < requests.size(); i++) {
total_distance += abs(requests[i] - current_track);
current_track = requests[i];
}
return total_distance;
}
// SSTF算法
int sstf(vector<int>& requests, int start) {
int total_distance = 0;
int current_track = start;
while (!requests.empty()) {
int min_distance = INT_MAX;
int min_index = -1;
for (int i = 0; i < requests.size(); i++) {
int distance = abs(requests[i] - current_track);
if (distance < min_distance) {
min_distance = distance;
min_index = i;
}
}
total_distance += min_distance;
current_track = requests[min_index];
requests.erase(requests.begin() + min_index);
}
return total_distance;
}
// SCAN算法
int scan(vector<int>& requests, int start, int max_track) {
int total_distance = 0;
int current_track = start;
bool direction = true; // true表示向内移动,false表示向外移动
while (!requests.empty()) {
if (current_track == max_track) {
direction = false;
} else if (current_track == 0) {
direction = true;
}
if (direction) {
auto it = find_if(requests.begin(), requests.end(), [current_track](int track) {
return track >= current_track;
});
if (it != requests.end()) {
total_distance += *it - current_track;
current_track = *it;
requests.erase(it);
} else {
total_distance += max_track - current_track;
current_track = max_track;
}
} else {
auto it = find_if(requests.rbegin(), requests.rend(), [current_track](int track) {
return track <= current_track;
});
if (it != requests.rend()) {
total_distance += current_track - *it;
current_track = *it;
requests.erase((it + 1).base());
} else {
total_distance += current_track;
current_track = 0;
}
}
}
return total_distance;
}
// C-SCAN算法
int cscan(vector<int>& requests, int start, int max_track) {
int total_distance = 0;
int current_track = start;
while (!requests.empty()) {
auto it = find_if(requests.begin(), requests.end(), [current_track](int track) {
return track >= current_track;
});
if (it != requests.end()) {
total_distance += *it - current_track;
current_track = *it;
requests.erase(it);
} else {
total_distance += max_track - current_track;
current_track = 0;
}
}
return total_distance;
}
int main() {
vector<int> requests = {98, 138, 37, 122, 14, 124, 65, 67};
int start_track = 53;
int max_track = 199;
int fcfs_distance = fcfs(requests, start_track);
int sstf_distance = sstf(requests, start_track);
int scan_distance = scan(requests, start_track, max_track);
int cscan_distance = cscan(requests, start_track, max_track);
cout << "FCFS算法平均寻道长度:" << fcfs_distance << endl;
cout << "SSTF算法平均寻道长度:" << sstf_distance << endl;
cout << "SCAN算法平均寻道长度:" << scan_distance << endl;
cout << "C-SCAN算法平均寻道长度:" << cscan_distance << endl;
return 0;
}
```
阅读全文