C語言寫的磁碟排程演算法,歡迎大家來討論
ZHUO_SIR發表於2018-05-22
- #include<iostream>
- #include<cstdio>
- #include<algorithm>
- #include<cmath>
- using namespace std;
- const int maxn = 100;
- int n, now, s, sum, nnow, everage, p[maxn], b[maxn], sp[maxn], lenp[maxn];
-
- void show()
- {
- sum = 0;
- cout <<" 被訪問的下一磁軌號 移動距離(磁軌數)\n";
- for(int i = 0;i < n; ++i)
- {
- printf(" %3d %3d\n", sp[i], lenp[i]);
- sum += lenp[i];
- }
- cout <<" 平均尋道長度: "<<(double)sum/n <<"\n";
- }
-
- void FCFS()
- {
- for(int i = 0;i < n; ++i)
- {
- sp[i] = p[i];
- if(i) lenp[i] = abs(sp[i-1] - sp[i]);
- else lenp[i] = abs(now - sp[i]);
- }
- }
-
- void SSTF()
- {
- nnow = now;
- int fl[maxn] = {0};
- for(int i = 0;i < n; ++i)
- {
- int minx = 999999, pp;
- for(int j = 0;j < n; ++j)
- {
- if(!fl[j] && abs(nnow - p[j]) < minx)
- {
- minx = abs(nnow - p[j]);
- pp = j;
- }
- }
- sp[i] = p[pp];
- lenp[i] = minx;
- nnow = p[pp];
- fl[pp] = 1;
- }
- }
-
- bool cmp(int a, int b)
- {
- return a > b;
- }
- void SCAN()
- {
- nnow = now;
- int aa[maxn], bb[maxn], ak = 0, bk = 0;
- for(int i = 0;i < n; ++i)
- {
- if(p[i] < nnow) aa[ak++] = p[i];
- else bb[bk++] = p[i];
- }
- sort(aa, aa+ak,cmp);
- sort(bb, bb+bk);
- int i = 0;
- for(int j = 0;j < bk; ++j)
- {
- sp[i] = bb[j];
- lenp[i++] = bb[j] - nnow;
- nnow = bb[j];
- }
- for(int j = 0;j < ak; ++j)
- {
- sp[i] = aa[j];
- lenp[i++] = nnow - aa[j];
- nnow = aa[j];
- }
- }
-
- void CSCAN()
- {
- nnow = now;
- int aa[maxn], bb[maxn], ak = 0, bk = 0;
- for(int i = 0;i < n; ++i)
- {
- if(p[i] < nnow) aa[ak++] = p[i];
- else bb[bk++] = p[i];
- }
- sort(aa, aa+ak);
- sort(bb, bb+bk);
- int i = 0;
- for(int j = 0;j < bk; ++j)
- {
- sp[i] = bb[j];
- lenp[i++] = bb[j] - nnow;
- nnow = bb[j];
- }
- for(int j = 0;j < ak; ++j)
- {
- sp[i] = aa[j];
- lenp[i++] = abs(aa[j] - nnow);
- nnow = aa[j];
- }
- }
- int main()
- {
- xbegin:
- cout<<"請輸入被訪問的總磁軌數: ";
- cin >> n;
- if(n <= 0 || n > 100)
- {
- cout <<"輸入不合法,請重新輸入!\n";
- goto xbegin;
- }
- nowCD:
- cout <<"請輸入當前磁軌: ";
- cin >> now;
- if(now < 0)
- {
- cout <<"磁軌不存在,請重新輸入!";
- goto nowCD;
- }
- pCD:
- cout <<"請按順序輸入所有需要訪問的磁軌:";
- for(int i = 0;i < n; ++i) cin >> p[i];
- for(int i = 0;i < n; ++i)
- {
- b[i] = p[i];
- if(p[i] < 0)
- {
- cout <<"輸入中有不存在的磁軌,請重新輸入!\n";
- goto pCD;
- }
- }
- serve:
- cout <<" 1、先來先服務演算法(FCFS)\n";
- cout <<" 2、最短尋道優先演算法(SSTF)\n";
- cout <<" 3、掃描演算法(SCAN)\n";
- cout <<" 4、迴圈掃描演算法(CSCAN)\n";
- cout <<"請輸入所用磁碟排程的演算法: ";
- cin >> s;
- if(s < 1 || s > 4)
- {
- cout <<"輸入有誤,請重新輸入!\n";
- goto serve;
- }
- work:
- for(int i = 0;i < n; ++i) p[i] = b[i];
- if(s == 1) FCFS();
- else if(s == 2) SSTF();
- else if(s == 3) SCAN();
- else CSCAN();
- show();
- xend:
- char ch;
- cout <<"重新選擇演算法或重新輸入資料?(輸入Y選擇演算法,輸入y重新輸入資料): ";
- cin >> ch;
- if(ch == 'Y') goto serve;
- else if(ch == 'y') goto xbegin;
- else cout <<"程式結束,謝謝使用!\n";
- return 0;
- }