C++实现SSTF算法,计算扫描长度
时间: 2023-08-12 17:14:07 浏览: 90
SSTF(Shortest Seek Time First)算法是磁盘调度算法中的一种,它选择离当前磁头位置最近的磁道进行访问。下面是C++实现SSTF算法,计算扫描长度的示例代码:
```c++
#include <iostream>
#include <cstdlib>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int n, head, sum = 0;
vector<int> request;
cout << "请输入磁盘请求队列长度:";
cin >> n;
cout << "请输入磁盘请求队列:";
for (int i = 0; i < n; i++)
{
int x;
cin >> x;
request.push_back(x);
}
cout << "请输入磁头初始位置:";
cin >> head;
while (!request.empty())
{
int index = -1, min_dist = INT_MAX;
for (int i = 0; i < request.size(); i++)
{
int dist = abs(request[i] - head);
if (dist < min_dist)
{
min_dist = dist;
index = i;
}
}
sum += min_dist;
head = request[index];
request.erase(request.begin() + index);
}
cout << "扫描长度为:" << sum << endl;
return 0;
}
```
该代码首先读入磁盘请求队列的长度和队列中的请求,然后读入磁头的初始位置。接着在循环中,每次找到离磁头最近的请求,将其添加到扫描序列中,然后将磁头移动到该请求所在的磁道,并将该请求从队列中删除。最后输出扫描长度即可。
阅读全文