操作系统 磁盘调度---循环扫描(CSCAN)算法(C++实现 操作系统实验)

思路:

自里向外移动,当磁头移到最外的磁道并访问后,磁头立即返回到最里的欲访问磁道,即将最小磁道号紧接着最大磁道号构成循环,进行循环扫描

代码如下:

#include
#include
#include
#include
#include

using namespace std;
int n;
int start;
int xb;
typedef pair p;
vector

v; vector seq; const int INF = 0x3f3f3f3f; double avgfind; int main() { cout << "请输入磁道个数:" << "\n"; cin >> n; int temp = n; cout << "请输入开始磁道号:" << "\n"; cin >> start; int x; cout << "请依次输入" << n << "个磁道号" << "\n"; for(int i = 1; i <= n; i ++) { cin >> x; seq.push_back(x); } sort(seq.begin(), seq.end()); if(seq[0] > start) { v.push_back({seq[0], abs(seq[0] - start)}); avgfind += abs(seq[0] - start); start = seq[0]; xb = 1; for(int i = xb; i < seq.size(); i ++) { v.push_back({seq[i], abs(seq[i] - start)}); avgfind += abs(seq[i] - start); start = seq[i]; } } else if(seq[n - 1] < start) { v.push_back({seq[n - 1], abs(start - seq[n - 1])}); avgfind += abs(start - seq[n - 1]); xb = n - 2; start = seq[n - 1]; for(int i = xb; i >= 0; i --) { v.push_back({seq[i], abs(seq[i] - start)}); avgfind += abs(seq[i] - start); start = seq[i]; } } else { for(int i = 0; i < seq.size() - 1; i ++) { if(seq[i + 1] > start && seq[i] < start) { v.push_back({seq[i + 1], abs(seq[i + 1] - start)}); avgfind += abs(seq[i + 1] - start); start = seq[i + 1]; xb = (i + 2 > seq.size()) ? seq.size() : (i + 2); break; } } for(int i = xb; i < seq.size(); i ++) { v.push_back({seq[i], abs(seq[i] - start)}); avgfind += abs(seq[i] - start); start = seq[i]; } for(int i = 0; i <= xb - 2; i ++) { v.push_back({seq[i], abs(seq[i] - start)}); avgfind += abs(seq[i] - start); start = seq[i]; } } cout << "\n"; cout << "磁道号\t移动距离" << "\n"; for(int i = 0; i < v.size(); i ++) { cout << v[i].first << "\t" << v[i].second << "\n"; } cout << "平均寻道长度:" << "\t"; printf("%.2lf", avgfind / temp); return 0; }

你可能感兴趣的:(操作系统,c++,算法)